`
net_secret
  • 浏览: 23992 次
社区版块
存档分类
最新评论

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

阅读更多
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);
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics