如何在Java中为Android设置HttpResponse超时

本文翻译自:How to set HttpResponse timeout for Android in Java

I have created the following function for checking the connection status: 我创建了以下用于检查连接状态的函数:

private void checkConnectionStatus() {
    HttpClient httpClient = new DefaultHttpClient();

    try {
      String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
                   + strSessionString + "/ConnectionStatus";
      Log.d("phobos", "performing get " + url);
      HttpGet method = new HttpGet(new URI(url));
      HttpResponse response = httpClient.execute(method);

      if (response != null) {
        String result = getResponse(response.getEntity());
        ...

When I shut down the server for testing the execution waits a long time at line 当我关闭服务器进行测试时,执行会等待很长时间

HttpResponse response = httpClient.execute(method);

Does anyone know how to set the timeout in order to avoid waiting too long? 有谁知道如何设置超时以避免等待太久?

Thanks! 谢谢!


#1楼

参考:https://stackoom.com/question/2uXV/如何在Java中为Android设置HttpResponse超时


#2楼

To set settings on the client: 要在客户端上设置设置:

AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
HttpConnectionParams.setSoTimeout(client.getParams(), 5000);

I've used this successfully on JellyBean, but should also work for older platforms .... 我已经在JellyBean上成功使用了它,但也适用于旧平台....

HTH HTH


#3楼

In my example, two timeouts are set. 在我的示例中,设置了两个超时。 The connection timeout throws java.net.SocketTimeoutException: Socket is not connected and the socket timeout java.net.SocketTimeoutException: The operation timed out . 连接超时抛出java.net.SocketTimeoutException: Socket is not connected且套接字超时java.net.SocketTimeoutException: The operation timed out

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (eg DefaultHttpClient or AndroidHttpClient) you can use the function setParams() . 如果要设置任何现有HTTPClient的参数(例如DefaultHttpClient或AndroidHttpClient),可以使用函数setParams()

httpClient.setParams(httpParameters);

#4楼

HttpParams httpParameters = new BasicHttpParams();
            HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParameters,
                    HTTP.DEFAULT_CONTENT_CHARSET);
            HttpProtocolParams.setUseExpectContinue(httpParameters, true);

            // Set the timeout in milliseconds until a connection is
            // established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = 35 * 1000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 30 * 1000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

#5楼

If you are using the HttpURLConnection , call setConnectTimeout() as described here : 如果您正在使用HttpURLConnection ,请按照此处所述调用setConnectTimeout()

URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);

#6楼

you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well. 你可以通过Httpclient-android-4.3.5的方式创建HttpClient实例,它可以很好地工作。

 SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
                RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
        CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章