Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict Mode complains on resource leak

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.

like image 957
muneikh Avatar asked Dec 21 '22 12:12

muneikh


1 Answers

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();
like image 102
Tspoon Avatar answered Jan 03 '23 14:01

Tspoon