【问题标题】:Android HTTP Request Making App IrresponsiveAndroid HTTP 请求使应用程序无响应
【发布时间】:2014-01-05 19:04:43
【问题描述】:

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

    }
}

【问题讨论】:

  • 当从 UI 线程做网络 IO 时,只要操作需要,App 就会冻结。完成后,应用程序应再次响应。考虑在另一个线程中执行阻塞操作,例如通过AsyncTask

标签: android androidhttpclient


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可能正在 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) {}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 2020-02-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多