如何在AsyncTask android中处理HttpResponse

时间:2013-04-21 16:56:22

标签: android android-asynctask

我的活动使用AsynTask执行http请求。 如果web-server没有回答,如何处理HttpResponse? 目前,当我的Web服务器关闭时,AsynTask刚停在“HttpResponse response = client.execute(httppost);”然后什么都不做我需要处理这个响应并做一些事情,但是不执行“执行”下面的代码。

这是ny后台任务:

    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        String result = null;
        try {
            // Add your data
            List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
            postData.add(new BasicNameValuePair("session_id", session_id));
            postData.add(new BasicNameValuePair("i_key", params[0]));

            HttpPost httppost = new HttpPost( "http://my.webserver.com/getInfo.php");
            httppost.setEntity(new UrlEncodedFormEntity(postData));

            HttpResponse response = client.execute(httppost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(responseEntity.getContent(),
                                "UTF-8"));
                result = reader.readLine().toString();
            } else {
              Toast.makeText(this, "DDDDDDD",Toast.LENGTH_LONG).show();
            }

        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        return result;
    }

如果网络服务器关闭而不回复,我如何处理响应?

1 个答案:

答案 0 :(得分:3)

您需要为客户端的连接设置超时。例如:

protected String doInBackground(String... params) {
    HttpParams httpParameters = new BasicHttpParams();
    // set the connection timeout and socket timeout parameters (milliseconds)
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 5000);

    HttpClient client = new DefaultHttpClient(httpParameters);
    . . . // the rest of your code
}