问题描述:

I face a ConnectionPoolTimeOutException recently, and I am wondering if it relates to my response handler. If response entity is resource and should be freed as soon as it is not needed, why the Apache BasicResponseHandler does not consume entity before return response string?

@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);

}

}

网友答案:

Because it is taken care of by CloseableHttpClient

网友答案:
BasicResponseHandler: 
    if status is greater than 300
        invokes EntityUtils.consume(); 
    else 
        invokes EntityUtils.toString();

If you look at those two methods, both of them closes the Inputstream as shown below.

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;
    }
}
相关阅读:
Top