Reputation: 362
I have a method named getResponse()
in my program:
public ClosableHTTPResponse getResponse()
{
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120 * 1000).build();
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
HttpGet httpPostRequest = new HttpGet(getURL);
httpPostRequest.addHeader("Authorization", "Token " + APIKey);
httpPostRequest.setHeader("Content-type", "application/json");
response = httpClient.execute(httpPostRequest);
String statusLine = response.getStatusLine().toString();
System.out.println("Status Line Response: " + statusLine);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) response.close();
if (httpClient != null) httpClient.close();
}
return response;
}
}
When I call this method from external method in the following code:
public void analzyeReponseA()
{
CloseableHttpResponse response = null;
try {
response = getResponse("p1", "p2");
String OKResponse = "HTTP/1.1 200 OK";
String statusLine = response.getStatusLine().toString();
if (statusLine.contains(OKResponse)) {
HttpEntity entity = response.getEntity();
// java.net.SocketException: Socket is closed exception thrown on next line..
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println("Response String:\n" + responseString);
}
}
I'm getting a java.net.SocketException: Socket is closed
exception
on this line:
String responseString = EntityUtils.toString(entity, "UTF-8");
Based on this and this thread, presumably this is happening bec I call if (response != null) response.close();
in getResponse()
method (correct?)
If so, my question now is how do I return a CloseableHttpResponse
without the program throwing above exception? Is the only option to call String responseString = EntityUtils.toString(entity, "UTF-8");
in getReponse()
method and return a responseString
instead of CloseableHttpResponse
? What if I still want to access the response
object in caller code (like to check status line or something else)?
Upvotes: 3
Views: 9158
Reputation: 4403
If I understood the question correctly, I'd first look to see if the code really needed to return an HttpResponse
. If the method(s) that call getResponse()
all only need, e.g, the contents, then return the contents rather than the response.
Otherwise, you should be able to do, using the try-with-resources approach:
public void callingMethod() {
try (CloseableHttpResponse resp = getResponse();) {
{
// example
HttpEntity entity = resp.getEntity();
}
}
And remove the close from the getResponse()
method.
Also, you do not want to be opening/closing the HttpClient on each invocation. That class is designed to be used multiple times. There is more information at You're Using HttpClient wrong and it is destabilizing your software. Thus, you may wish to refactor the code to move the HttpClient
elsewhere.
Upvotes: 1