I am using HttpClient 4.1.2. Setting ConnectionTimeout and SocketTimeout to a value is never effective.
code :
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();
}
If the server is down, then the connection timeout is never before 400 ms when it has to timeout at ~ 30 ms as configured.
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.
Can anyone suggest how to configure HttpClient 4.1.2 so that it times out around the configured time?
解决方案
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);
在使用HttpClient 4.1.2时,设置连接超时和socket超时并未按预期生效。代码示例中,即使配置了30ms的连接超时和60ms的socket超时,当服务器不可用时,实际超时时间远高于配置值。问题在于HttpConnectionParams需要传递给连接管理器。正确的做法是将超时参数设置到连接管理器,如:httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); 这样可以确保超时设置按预期工作。
8589

被折叠的 条评论
为什么被折叠?



