代码之家  ›  专栏  ›  技术社区  ›  JoonT

HttpClient SockettTimeoutException处理

  •  0
  • JoonT  · 技术社区  · 6 年前

    我从中获取数据 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.
    这很有道理,但我不知道如何处理。

    1 回复  |  直到 6 年前
        1
  •  0
  •   piy26    6 年前

    问题所在

    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