Sha*_*han 6 java apache-httpclient-4.x
我正在使用HttpClient 4.1.2.将ConnectionTimeout和SocketTimeout设置为值永远不会有效.
代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
如果服务器关闭,那么连接超时永远不会超过400毫秒,当它必须按照配置超时~30毫秒时.
套接字超时的情况也是如此,将睡眠放入doGet()5000毫秒将抛出一个套接字超时,它将永远不会达到配置的60毫秒左右.它需要超过500毫秒.
任何人都可以建议如何配置HttpClient 4.1.2,以便它在配置的时间周围超时?
Vla*_*lad 13
将HttpConnectionParams需要被传递给连接管理器(见这个问题).使用时,DefaultHttpClient您可以像这样设置这些参数:
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
Run Code Online (Sandbox Code Playgroud)
另请参阅文档!
小智 7
你可以尝试这个(适用于apache http-client 4.5.2):
int DEFAULT_TIMEOUT = 5000;
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_TIMEOUT)
.setConnectionRequestTimeout(DEFAULT_TIMEOUT)
.setSocketTimeout(DEFAULT_TIMEOUT)
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
Run Code Online (Sandbox Code Playgroud)