严格模式会抱怨以下内容:在附加的堆栈跟踪中获取资源但从未释放。有关避免资源泄漏的信息,请参阅java.io.Closeable。
**response = httpclient.execute(httpPost);**
以下是我的代码:
HttpClient httpclient = new DefaultHttpClient();
String url = "example";
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
String responseString = "";
try {
httpPost.setHeader("Content-Type", "application/json");
**response = httpclient.execute(httpPost);**
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return responseString;
提前致谢。
答案 0 :(得分:5)
从4.3开始,kenota指出的方法已被弃用。
现在应该使用HttpClient
而不是CloseableHttpClient
,如下所示:
CloseableHttpClient client= HttpClientBuilder.create().build();
然后您可以使用以下方法关闭它:
client.close();
答案 1 :(得分:4)
正如Praful Bhatanagar指出的那样,你需要在 finally 块中释放资源:
HttpClient httpclient = new DefaultHttpClient();
//... code skipped
String responseString = "";
try {
//... code skipped
} catch (IOException e) {
} finally {
httpClient.getConnectionManager().shutdown();
}