Question

Strict mode complains the following: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.:

**response = httpclient.execute(httpPost);**

Below is my code:

    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;

Thanks in advance.

Was it helpful?

Solution 2

As Praful Bhatanagar pointed out, you need to release resources in finally block:

HttpClient httpclient = new DefaultHttpClient();
//... code skipped
String responseString = "";
try {
//... code skipped
} catch (IOException e) {
} finally {
     httpClient.getConnectionManager().shutdown();
}

OTHER TIPS

As of 4.3 the method pointed out by kenota is deprecated.

Instead of HttpClient you should now use CloseableHttpClient as shown below:

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

Then you can close it using:

    client.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top