Reputation: 21971
I'm sorry for a little duplication, here, here, but they say, that if you read the the last byte of the body of response and close the input stream. It is ready for another request. But look what I got here, and I always get this error when executing a new request.
Invalid use of SingleClientConnManager: connection still allocated
public String detectGooglePost(String text) throws SystemException {
List<NameValuePair> qParams = new ArrayList<NameValuePair>();
qParams.add(new BasicNameValuePair("key", key));
List<NameValuePair> bodyParams = new ArrayList<NameValuePair>();
bodyParams.add(new BasicNameValuePair("q", text));
HttpPost httpPost = new HttpPost(createURI(qParams));
httpPost.addHeader("X-HTTP-Method-Override", "GET");
try {
httpPost.setEntity(new UrlEncodedFormEntity(bodyParams));
} catch (UnsupportedEncodingException e) {
throw new SystemException("Problem when buidling Google request entity", e);
}
String language = getLanguage(httpPost);
return language;
}
private String getLanguage(HttpUriRequest request) throws SystemException {
HttpResponse response;
try {
response = httpclient.execute(request);
} catch (Exception e) {
throw new SystemException("Problem when executing Google request", e);
}
int sc = response.getStatusLine().getStatusCode();
if (sc != HttpStatus.SC_OK)
throw new SystemException("google status code : " + sc);
StringBuilder builder = getBuilder(response);
String language = processJson(builder.toString());
return language;
}
private StringBuilder getBuilder(HttpResponse response) throws SystemException {
HttpEntity entity = response.getEntity();
if (entity == null)
throw new SystemException("response entity null");
StringBuilder builder = new StringBuilder();
BufferedReader in = null;
String str;
try {
in = new BufferedReader(new InputStreamReader(entity.getContent()));
while ((str = in.readLine()) != null)
builder.append(str);
} catch (IOException e) {
throw new SystemException("Reading input stream of http google response entity problem", e);
} finally {
IOUtils.closeQuietly(in);
}
if (builder.length() == 0)
throw new SystemException("content stream of response entity empty has zero length");
return builder;
}
How should I release the connection ? The stream is read and closed. But still when detectGooglePost(text) method is called again (singleton HttpClient instance), it throws that error.
Upvotes: 1
Views: 1952
Reputation: 21971
Man it must work, try this :
HttpResponse response;
String responseBody;
try {
response = httpclient.execute(request);
int sc = response.getStatusLine().getStatusCode();
if (sc != HttpStatus.SC_OK)
throw new SystemException("google status code : " + sc);
HttpEntity entity = response.getEntity();
if (entity == null)
throw new SystemException("response entity null");
responseBody = EntityUtils.toString(entity);
} catch (Exception e) {
request.abort();
throw new SystemException("Problem when executing Google request", e);
}
Upvotes: 1