// General query of the website. Takes an object of type Q and returns one of class R.
public static <Q extends JSONObject, R> R query(String urlBase, String op, Q q, Class<R> r) throws IOException {
// The request.
final HttpRequestBase request;
//postRequest.addHeader("Accept-Encoding", "gzip,deflate");
if (q != null) {
// Prepare the post.
HttpPost postRequest = new HttpPost(urlBase + op);
// Get it all into a JSON string.
StringEntity input = new StringEntity(asJSONString(q));
input.setContentType("application/json");
postRequest.setEntity(input);
// Use that one.
request = postRequest;
} else {
// Just get.
request = new HttpGet(urlBase + op);
}
log.debug("> " + urlBase + op + (q == null ? "" : " " + q));
// Post it and wait.
return readResponse(request, HttpClientPool.getClient().execute(request), r);
}
public static <R> R readResponse(HttpRequestBase request, CloseableHttpResponse response, Class<R> r) throws IOException {
// What was read.
R red = null;
InputStream content = null;
try {
// What happened?
if (response.getStatusLine().getStatusCode() == 200) {
// Roll out the results
JsonParserHttpEntity rsp;entity = response.getEntity();
contentif (entity != response.getEntity(null) {
InputStream content = entity.getContent();
try {
// Roll it directly from the response stream.
JsonParser rsp = getFactory().createJsonParser(content);
// Bring back the response.
red = rsp.readValueAs(r);
} finally {
// Always close the content.
content.close();
}
}
} else {
// The finally below will clean up.
throw new IOException("HTTP Response: " + response.getStatusLine().getStatusCode());
}
} finally {
// Always close the response.
response.close();
// Reset the request.
request.reset();
}
if (red == null) {
log.debug("< {null}");
} else {
log.debug("< {}", red.getClass().isArray() ? Arrays.toString((Object[]) red) : red.toString());
}
return red;
}
org.apache.http.NoHttpResponseException: The target server failed to respond
java.net.BindException: Address already in use: connect
java.net.SocketException: No buffer space available (maximum connections reached?): connect -- Thousands of these per hour!!!
Am I using the pool correctly?
Am I closing/not closing at the right time?
Should I reset the request (request.reset())?
Should the InputStream content be closed?
Have I missed something?
Also - failing to close the stream and checking the entity against null.