Android HTTP请求使应用程序无响应

时间:2014-01-05 19:04:43

标签: android androidhttpclient

我想对从文本框中提取的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();

    }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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

来完成

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) {}
}