我的程序中有一个名为</img>
的方法:
getResponse()
当我在以下代码中从外部方法调用此方法时:
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;
}
}
我遇到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);
}
}
异常
在这一行:
java.net.SocketException: Socket is closed
基于this和this线程,大概是因为我在String responseString = EntityUtils.toString(entity, "UTF-8");
方法中调用if (response != null) response.close();
(正确吗?) >
如果是这样,我现在的问题是如何在程序不引发异常的情况下返回getResponse()
?在CloseableHttpResponse
方法中调用String responseString = EntityUtils.toString(entity, "UTF-8");
并返回getReponse()
而不是responseString
的唯一选择吗?如果我仍然想访问调用者代码中的CloseableHttpResponse
对象(例如检查状态行或其他内容)怎么办?
答案 0 :(得分:0)
如果我正确理解了这个问题,那么我首先来看一下代码是否真的需要返回HttpResponse
。如果所有调用getResponse()
的方法只需要例如内容,则返回内容而不是响应。
否则,您应该可以使用try-with-resources方法进行操作:
public void callingMethod() {
try (CloseableHttpResponse resp = getResponse();) {
{
// example
HttpEntity entity = resp.getEntity();
}
}
然后从getResponse()
方法中删除关闭。
此外,您不想在每次调用时都打开/关闭HttpClient。该类被设计为可以多次使用。 You're Using HttpClient wrong and it is destabilizing your software上有更多信息。因此,您可能希望重构代码以将HttpClient
移动到其他位置。