Java:HttpClient 4.1.2:ConnectionTimeout,SocketTimeout值设置无效 [英] Java : HttpClient 4.1.2 : ConnectionTimeout, SocketTimeout values set are not effective

查看:1049
本文介绍了Java:HttpClient 4.1.2:ConnectionTimeout,SocketTimeout值设置无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HttpClient 4.1.2。将ConnectionTimeout和SocketTimeout设置为值永远不会有效。

I am using HttpClient 4.1.2. Setting ConnectionTimeout and SocketTimeout to a value is never effective.

代码:

  Long startTime = null;
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpParams params = httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(params, 30);
  HttpConnectionParams.setSoTimeout(params, 60);      
   HttpGet httpget = new HttpGet("http://localhost:8080/Test/ScteServer");        
      try {         
        startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(httpget);
      }
      catch(SocketTimeoutException se) {
        Long endTime = System.currentTimeMillis();
        System.out.println("SocketTimeoutException :: time elapsed :: " + (endTime-startTime));
        se.printStackTrace();
      }          
      catch(ConnectTimeoutException cte) {
        Long endTime = System.currentTimeMillis();
        System.out.println("ConnectTimeoutException :: time elapsed :: " + (endTime-startTime));
        cte.printStackTrace();
      }
      catch (ClientProtocolException e) {            
        e.printStackTrace();
      }
      catch (IOException e) {
        Long endTime = System.currentTimeMillis();
        System.out.println("IOException :: time elapsed :: " + (endTime-startTime) );            
        e.printStackTrace();
      }       

如果服务器关闭,那么连接超时永远不会超过400毫秒它必须在配置时超过~30 ms。

If the server is down, then the connection timeout is never before 400 ms when it has to timeout at ~ 30 ms as configured.

Socket Timeout的情况相同,在doGet()中休眠5000毫秒会抛出一个套接字超时将永远不会在配置的大约60毫秒。它需要超过500毫秒。

Same is the case for Socket Timeout, putting a sleep in doGet() for 5000 ms will throw a socket timeout which will never be at around 60 ms as configured. It takes more than 500 ms.

任何人都可以建议如何配置HttpClient 4.1.2,使其在配置的时间内超时?

Can anyone suggest how to configure HttpClient 4.1.2 so that it times out around the configured time?

推荐答案

需要将 HttpConnectionParams 传递给连接管理器(参见这个问题)。使用 DefaultHttpClient 时,您可以设置以下参数:

The HttpConnectionParams need to be passed to a connection manager (see this question). When using the DefaultHttpClient you can set these parameters like this:

    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

参见文档也是!

这篇关于Java:HttpClient 4.1.2:ConnectionTimeout,SocketTimeout值设置无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆