0

我想对从文本框中获取的 URL 进行简单的 HTTP 头请求。每次我输入 URL 并单击以获取 HTTP 响应时,应用程序都会变得无响应。这是代码:

public  void    MakeRequest(View v)
{
    EditText mEdit;
    TextView txtresponse;
    txtresponse = (TextView)findViewById(R.id.textView1);
    mEdit = (EditText)findViewById(R.id.editText1);
    HttpClient httpClient = new DefaultHttpClient();
    HttpHead httphead = new HttpHead(mEdit.getText().toString());

    try {
        HttpResponse response = httpClient.execute(httphead);
        txtresponse.setText(response.toString());
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    }
}
4

2 回答 2

1

永远不要在 UI 线程上执行长时间运行的任务(由于服务器延迟,HTTP 请求/响应可能需要很长时间)。在后台线程中运行 HTTP 处理。Stackoverflow 上有几个例子——比如用 android 发出 HTTP 请求,当然也可以在 Android 网站上阅读——http: //developer.android.com/training/articles/perf-anr.html

于 2014-01-05T19:18:33.477 回答
0

您可能正在 UI 线程中执行请求。这是不好的做法,因为它负责为 UI 完成的所有工作。您可以在此处阅读有关此内容的更多信息。

更好的方法是在另一个线程中执行此操作。这可以通过例如

  • 自定义工作线程或
  • 一个AsyncTask

带有 an 的示例AsyncTask(这在您的课程中):

public void MakeRequest(View v)
{
    EditText mEdit;
    mEdit = (EditText)findViewById(R.id.editText1);
    new RequestTask().execute(mEdit.getText().toString());
}

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

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpHead httphead = new HttpHead(params[0]);

        try {
            HttpResponse response = httpClient.execute(httphead);
            return response.toString();
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        TextView txtresponse;
        txtresponse = (TextView)findViewById(R.id.textView1);
        txtresponse.setText(result);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}
于 2014-01-05T19:17:52.477 回答