我正在使用google-api-client-java 1.2.1-alpha执行POST请求,并在执行HttpRequest时获得以下stacktrace。
在我捕获并忽略先前POST到同一URL的403错误后立即发生,并重新使用传输进行后续请求。 (它在一个循环中向同一个ATOM提要插入多个条目)。
403之后我应该做些什么来“清理”?
Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:199)
at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:173)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:390)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.google.api.client.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:47)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:207)
at au.com.machaira.pss.gape.RedirectHandler.execute(RedirectHandler.java:38)
at au.com.machaira.pss.gape.ss.model.records.TableEntry.executeModification(TableEntry.java:81)
为什么我下面的代码会尝试获取新的连接?
答案 0 :(得分:80)
在重新连接另一个请求之前,您需要使用响应正文。您不仅应该读取响应状态,还应该将响应InputStream
完全读取到最后一个字节,从而忽略读取的字节。
答案 1 :(得分:42)
在使用HttpClient和Jetty构建测试框架时,我遇到了类似的问题。我不得不从我的客户端向Servelet创建多个请求,但它在执行时给出了相同的异常。
我在http://foo.jasonhudgins.com/2010/03/http-connections-revisited.html
找到了替代方案您还可以使用以下方法来实例化您的客户端。
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
答案 2 :(得分:9)
类似的异常消息(因为至少Apache Jarkata Commons HTTP Client 4.2)是:
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
当两个或多个线程与单个org.apache.http.impl.client.DefaultHttpClient
进行交互时,可能会发生此异常。
如何在两个或多个线程可以与之交互而不会出现上述错误消息的情况下,如何制作4.2 DefaultHttpClient
实例线程安全( threadsafe )?以DefaultHttpClient
的形式向ClientConnectionManager
提供连接池org.apache.http.impl.conn.PoolingClientConnectionManager
!
/* using
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.2</version>
</dependency>
*/
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.apache.http.params.HttpParams;
import org.apache.http.client.methods.HttpGet;
public class MyComponent {
private HttpClient client;
{
PoolingClientConnectionManager conMan = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault() );
conMan.setMaxTotal(200);
conMan.setDefaultMaxPerRoute(200);
client = new DefaultHttpClient(conMan);
//The following parameter configurations are not
//neccessary for this example, but they show how
//to further tweak the HttpClient
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 15000);
}
//This method can be called concurrently by several threads
private InputStream getResource(String uri) {
try {
HttpGet method = new HttpGet(uri);
HttpResponse httpResponse = client.execute(method);
int statusCode = httpResponse.getStatusLine().getStatusCode();
InputStream is = null;
if (HttpStatus.SC_OK == statusCode) {
logger.debug("200 OK Amazon request");
is = httpResponse.getEntity().getContent();
} else {
logger.debug("Something went wrong, statusCode is {}",
statusCode);
EntityUtils.consume(httpResponse.getEntity());
}
return is;
} catch (Exception e) {
logger.error("Something went terribly wrong", e);
throw new RuntimeException(e);
}
}
}
答案 3 :(得分:8)
这是一个经常被问到的问题。 BalusC的回答是正确的。请抓住HttpReponseException,然后调用HttpResponseException。response。ignore()。如果您需要阅读错误消息,请使用response。parseAsString()如果您不知道响应内容类型,否则如果您确实知道内容类型使用响应。parseAs(MyType.class )。
YouTubeSample.java中来自youtube-jsonc-sample的简单代码段(虽然通常您会想要在实际应用中做更聪明的事情):
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
}
完全披露:我是google-api-java-client项目的所有者。
答案 4 :(得分:3)
我在单元测试中遇到了与jax-rs(resteasy)Response
对象相同的问题。
我通过致电response.releaseConnection();
解决了这个问题
releaseConnection() - Method仅在resteasy ClientResponse
对象上,因此我必须添加从Response
到ClientResponse
的强制转换。
答案 5 :(得分:0)
好吧,我有类似的问题,所有这些解决方案都不起作用,我在某些设备上测试过,问题是设备上的日期,它是2011年而不是2013年,检查这也可以提供帮助。
答案 6 :(得分:0)
试试这个
HttpResponse response = Client.execute(httpGet);
response.getEntity().consumeContent();
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
//task
Log.i("Connection", "OK");
}else{
Log.i("Connection", "Down");
}
答案 7 :(得分:0)
像这样读取InputStream:
if( response.getStatusLine().getStatusCode() == 200 ) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( content ), 8 );
String line;
while( ( line = bufferedReader.readLine() ) != null ) {
sb.append( line );
}
bufferedReader.close();
content.close();
} catch( Exception ex ) {
Log.e( "statusCode", ex.getMessage() + "" );
}
}
答案 8 :(得分:0)
只需消耗以下响应,即可解决问题
response.getEntity().consumeContent();