HttpClient SocketTimeoutException处理

时间:2018-04-25 03:22:38

标签: java httpclient socket-timeout-exception

我使用REST API serverHttpClient获取数据 现在我应该处理,因为API Server在10秒内无法得到任何回复 所以我按照

这样做了
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.
这很有道理,但我不知道如何处理。

1 个答案:

答案 0 :(得分:0)

问题

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