如何从我的Android应用程序发送http GET请求并检查响应

时间:2016-06-25 13:12:41

标签: android http get httpurlconnection

我是Android开发的新手,我需要一些 HttpURLConnection 的帮助。

我想要做的是发送http get请求(通过单击按钮),然后检查响应(检查响应我将TextView添加到我的主Activity)。

我的代码:

public class MainActivity extends AppCompatActivity {

private ProgressDialog progress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void sendGetRequest(View View) {
    new GetClass(this).execute();
}

private class GetClass extends AsyncTask<String, Void, Void> {

    private final Context context;

    public GetClass(Context c){
        this.context = c;
    }

    protected void onPreExecute(){
        progress= new ProgressDialog(this.context);
        progress.setMessage("Loading");
        progress.show();
    }

    @Override
    protected Void doInBackground(String... params) {

        String dataUrl = "http://myurl.com";
        String dataUrlParameters = "email="+"pp@gmail.com"+"&name="+"priyabrat";
        URL url;
        HttpURLConnection connection = null;

        try {
            final TextView outputView = (TextView) findViewById(R.id.showOutput);
            url = new URL(dataUrl);

            connection = (HttpURLConnection) url.openConnection();
            String urlParameters = "fizz=buzz";
            connection.setRequestMethod("GET");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");

            int responseCode = connection.getResponseCode();

            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
            output.append(System.getProperty("line.separator") + "Type " + "GET");
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while((line = br.readLine()) != null ) {
                responseOutput.append(line);
            }
            br.close();

            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    outputView.setText(output);
                    progress.dismiss();

                }
            });

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

}

问题是,当我运行我的应用程序并单击按钮&#34;发送GET请求&#34;时,应用程序正在停止并显示消息&#34;应用程序已停止&#34;

1 个答案:

答案 0 :(得分:0)

看看Android的一些Networking Librarys,他们会为你处理异步的东西:

如果您要自己动手,请查看Async Task中的doku( https://developer.android.com/reference/android/os/AsyncTask.html)并使用函数:

onPostExecute(String output)
  在后台计算完成后在UI线程上调用

。后台计算的结果作为参数传递给此步骤。

而不是:

 MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
         outputView.setText(output);
         progress.dismiss();
     }
 });

制作本:

return output;