2

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

这是任何后台任务:

    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;
    }

如果网络服务器已关闭且未回复,我如何处理响应?

4

1 回答 1

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
}
于 2013-04-21T17:05:15.817 回答