成功获取响应字符串后,为什么BasicResponseHandler不使用响应实体

时间:2015-11-02 14:40:59

标签: httpclient httpresponse apache-httpclient-4.x

我最近面临ConnectionPoolTimeOutException,我想知道它是否与我的响应处理程序有关。如果响应实体是资源并且应该在不需要时立即释放,为什么Apache 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);
    }

}

2 个答案:

答案 0 :(得分:0)

因为它由CloseableHttpClient

处理

答案 1 :(得分: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;
    }
}