4

严格模式抱怨以下内容:在附加的堆栈跟踪中获取了资源,但从未释放。有关避免资源泄漏的信息,请参阅 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;

提前致谢。

4

2 回答 2

7

从 4.3 开始,不推荐使用 kenota 指出的方法。

而不是HttpClient你现在应该使用CloseableHttpClient如下所示:

    CloseableHttpClient client= HttpClientBuilder.create().build();

然后你可以使用以下方法关闭它:

    client.close();
于 2014-01-09T20:31:08.350 回答
4

正如 Praful Bhatanagar 指出的,您需要在finally块中释放资源:

HttpClient httpclient = new DefaultHttpClient();
//... code skipped
String responseString = "";
try {
//... code skipped
} catch (IOException e) {
} finally {
     httpClient.getConnectionManager().shutdown();
}
于 2012-11-28T08:17:05.250 回答