首页 > 解决方案 > HttpClient SocketTimeoutException 处理

问题描述

我从REST API server使用中获取数据HttpClient
现在我应该处理超过 10 秒无法从API Server.
所以我做了如下

HttpClient httpClient = new DefaultHttpClient();

HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);

HttpPost httpPost = new HttpPost("api server address");
httpPost.setParams(...);

HttpResponse response;
try{
    response = httpClient.execute(httpPost);    
} catch(SocketTimeoutException e){
    httpPost.setParams(...); // change param
    response = httpClient.execute(httpPost);
}

它的发生就像
invalid use of singleclientconnmanager: connection still allocated.
它是有道理的,但我不知道如何处理。

标签: javahttpclientsocket-timeout-exception

解决方案


问题

invalid use of singleclientconnmanager: connection still allocated.

因为每当控制块进入异常块时调用execute() 方法两次,即出现任何异常时,就会发生这种情况。

try{
    // First Call
    response = httpClient.execute(httpPost);    
} catch(SocketTimeoutException e){
    httpPost.setParams(...); // change param
    //Second Call
    response = httpClient.execute(httpPost);
}

处理这个问题的优雅方法是使用 HTTPRequestRetryHandler http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d4e280


推荐阅读