使用httpclient的异常Httpclient 4.1.2:Invalid use of SingleClientConnManager

本文介绍了在使用Apache HttpClient进行HTTP请求时遇到的连接泄漏问题,详细解释了如何通过调用EntityUtils.consume(response.getEntity())来确保在分配新连接之前释放当前连接,从而解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Exception in thread “main” java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.

只要最后加上EntityUtils.consume(response.getEntity());就可以了!

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

public class SimpleResponseHandler implements ResponseHandler<Result> {

private HttpClient httpClient = null;
private String encoding = null;

public SimpleResponseHandler(HttpClient httpClient) {
this.httpClient = httpClient;
}

public Result handleResponse(HttpResponse response) throws IOException {
int statuscode = response.getStatusLine().getStatusCode();
if (isRedirectStatus(statuscode)) {
Header header = response.getFirstHeader("location");
if (header != null) {
String newuri = header.getValue();
if ((newuri == null) || (newuri.equals("")))
newuri = "/";
if (response.getEntity() != null)
EntityUtils.consume(response.getEntity());
return httpClient.doGet(newuri);
}
}
HttpEntity entity = response.getEntity();
if (entity != null) {
Result result = new Result(EntityUtils.toString(entity, encoding));
EntityUtils.consume(entity);
return result;
}
return null;
}

private boolean isRedirectStatus(int statuscode) {
return (statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值