2015-11-02 53 views
0

我最近遇到了ConnectionPoolTimeOutException,我想知道它是否與我的響應處理程序有關。如果響應實體是資源,並且在不需要時應儘快釋放,爲什麼Apache BasicResponseHandler在返回響應字符串之前不會消耗實體?爲什麼BasicResponseHandler在成功獲取響應字符串後沒有消耗響應實體

@Immutable 
public class BasicResponseHandler implements ResponseHandler<String> { 

    /** 
    * Returns the response body as a String if the response was successful (a 
    * 2xx status code). If no response body exists, this returns null. If the 
    * response was unsuccessful (>= 300 status code), throws an 
    * {@link HttpResponseException}. 
    */ 
    public String handleResponse(final HttpResponse response) 
      throws HttpResponseException, IOException { 
     StatusLine statusLine = response.getStatusLine(); 
     HttpEntity entity = response.getEntity(); 
     if (statusLine.getStatusCode() >= 300) { 
      EntityUtils.consume(entity); 
      throw new HttpResponseException(statusLine.getStatusCode(), 
        statusLine.getReasonPhrase()); 
     } 

     //Why not this: 
     //EntityUtils.consume(entity); 
     //String responseStr = entity == null ? null : EntityUtils.toString(entity); 
     //return responseStr; 

     return entity == null ? null : EntityUtils.toString(entity); 
    } 

} 

回答

0
BasicResponseHandler: 
    if status is greater than 300 
     invokes EntityUtils.consume(); 
    else 
     invokes EntityUtils.toString(); 

如果你看一下這兩種方法的照顧,他們都關閉的InputStream,如下圖所示。

public final class EntityUtils { 

    public static void consume(HttpEntity entity) throws IOException { 
     // .. 
     InputStream instream = entity.getContent(); 
     // .. 
     instream.close(); 
     //.. 
    } 

    public static String toString(HttpEntity entity, String defaultCharset) throws IOException, ParseException { 
     // .. 
     InputStream instream = entity.getContent(); 
     // ..  
     instream.close(); 

     return var9; 
    } 
}