处理Android中的HTTP连接中的响应延迟

时间:2014-10-07 09:01:04

标签: android httpconnection connection-timeout http-response-codes socket-timeout-exception

我正在发出HTTP请求。我想检查一下如果我在10秒内没有得到响应,我会退出循环。以下是我的代码。在发出HTTP请求时,最简单的方法是什么?建议欢迎。如果你能让我知道我应该在哪里包含这些建议,我的代码将非常有帮助。感谢

protected String doInBackground(String... params) {
        if (STATUS_STARTED != statusCode) {
            return null;
        }

        final HttpClient client = new DefaultHttpClient();                    


        String email = null;
        String url   = null;

        try {
            email = params[0];
            url   = params[1];

        } catch (ArrayIndexOutOfBoundsException e) {
            Log.e("LOG_TAG", "Invalid parameters are passed to task", e);
            statusCode = STATUS_BADPARAM;
            return null;
        }

        if ( (null == url) || (null == email)) {
            Log.e("LOG_TAG", "One of input params is null: url=" + url + "; email=" + email);
            statusCode = STATUS_BADPARAM;
            return null;
        }

        if(email != null){
            email = email.trim().replaceAll(" ", "");
            //email = email.toLowerCase(); 
            Log.d("EmailLowerCase", "EmailValidator" + email);
        }

        //url += REQUEST_PARAM_START + REQUEST_PARAM_EMAIL + email;
        url += email;

        Log.d("LOG_TAG", "Execute activation request to " + url);

        HttpGet getRequest = null;
        try {
            getRequest = new HttpGet(url);
        } catch (Exception e) {
            Log.e("LOG_TAG", e.getMessage());
        }

        try {
            try {
                int timeoutConnection = 10 * 1000;
                HttpConnectionParams.setConnectionTimeout(client.getParams(), timeoutConnection);
                Log.d("LOG_TAG", "Execute activation request to " + url);
                statusCode = STATUS_IN_PROGRESS;
                HttpResponse response = client.execute(getRequest);
                Log.d("LOG_TAG", "Activation request to " + url
                        + " completed");

                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                case HttpStatus.SC_MULTI_STATUS:
                case HttpStatus.SC_PARTIAL_CONTENT:
                case HttpStatus.SC_RESET_CONTENT:
                case HttpStatus.SC_CREATED:
                case HttpStatus.SC_ACCEPTED:
                case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
                    statusCode = STATUS_COMPLETED;
                    break;
                case HttpStatus.SC_GATEWAY_TIMEOUT:
                    statusCode = STATUS_GATEWAY_TIMEOUT;
                    return "-1";
                default:
                    Log.e("EmailValidator", "Error "
                            + response.getStatusLine().getStatusCode()
                            + " during activation, url=" + url);
                    statusCode = STATUS_ERROR;
                    break;
                }

                String responseStr = null;
                final HttpEntity entityResponse = response.getEntity();
                if (null != entityResponse) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    try {
                        inputStream = entityResponse.getContent();
                        outputStream = new BufferedOutputStream(dataStream,
                                IO_BUFFER_SIZE);
                        copy(inputStream, outputStream);
                        outputStream.flush();
                        responseStr = dataStream.toString();
                        return responseStr;

                    } finally {
                        if (null != inputStream) {
                            inputStream.close();
                        }
                        if (null != outputStream) {
                            outputStream.close();
                        }
                        if (null != dataStream) {
                            dataStream.close();
                        }
                        entityResponse.consumeContent();
                    }
                }
            } 
            catch (ConnectTimeoutException e) {
                getRequest.abort();
                Log.d("ConnectionTimeOut","Connection timout occured");
            } catch (IOException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "I/O error during activation, url=" + url, e);
            } catch (IllegalStateException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Incorrect URL: " + url);
            } catch (Exception e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Error during activation, url=" + url, e);
            }
        } catch (Exception e) {
            Log.e("LOG_TAG", "Error during activation, url=" + url, e);
        } catch (Throwable e) {
            Log.e("LOG_TAG", "Error during activation, url=" + url, e);
        }


        Log.e("LOG_TAG", TRANSMITTING_ERROR);
        return null;
    }

2 个答案:

答案 0 :(得分:1)

尝试添加 HttpConnection Timeout ,如下所示

int timeoutConnection = 10 * 1000;
HttpConnectionParams.setConnectionTimeout(client.getParams(),
                timeoutConnection);

修改

您可以检查catch块内是否会出现timout。见下文

 try {
                Log.d("LOG_TAG", "Execute activation request to " + url);
                statusCode = STATUS_IN_PROGRESS;
                HttpResponse response = client.execute(getRequest);
                Log.d("LOG_TAG", "Activation request to " + url
                        + " completed");

                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                case HttpStatus.SC_MULTI_STATUS:
                case HttpStatus.SC_PARTIAL_CONTENT:
                case HttpStatus.SC_RESET_CONTENT:
                case HttpStatus.SC_CREATED:
                case HttpStatus.SC_ACCEPTED:
                case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
                    statusCode = STATUS_COMPLETED;
                    break;
                case HttpStatus.SC_GATEWAY_TIMEOUT:
                    statusCode = STATUS_GATEWAY_TIMEOUT;
                    return "-1";
                default:
                    Log.e("EmailValidator", "Error "
                            + response.getStatusLine().getStatusCode()
                            + " during activation, url=" + url);
                    statusCode = STATUS_ERROR;
                    break;
                }

                String responseStr = null;
                final HttpEntity entityResponse = response.getEntity();
                if (null != entityResponse) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    try {
                        inputStream = entityResponse.getContent();
                        outputStream = new BufferedOutputStream(dataStream,
                                IO_BUFFER_SIZE);
                        copy(inputStream, outputStream);
                        outputStream.flush();
                        responseStr = dataStream.toString();
                        return responseStr;

                    } finally {
                        if (null != inputStream) {
                            inputStream.close();
                        }
                        if (null != outputStream) {
                            outputStream.close();
                        }
                        if (null != dataStream) {
                            dataStream.close();
                        }
                        entityResponse.consumeContent();
                    }
                }
            }catch (ConnectTimeoutException e) {
               Log.i("log","Connection timout occour");
            } catch (IOException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "I/O error during activation, url=" + url, e);
            } catch (IllegalStateException e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Incorrect URL: " + url);
            } catch (Exception e) {
                getRequest.abort();
                Log.e("LOG_TAG", "Error during activation, url=" + url, e);
            }

答案 1 :(得分:0)

参考这篇文章,它有关于AsyncTask.get()方法的详细信息,在这种情况下,可以在停止轮询服务器之前等待一段特定的时间: -

Android - Setting a Timeout for an AsyncTask?