0

I use HttpClient and have some trouble with it. Whether I want to get the entity or not, I need to release the HttpGet and the InputStream manually. Is there any way to release resource automatically such as 'try-with-resources' in Java 7 for HttpClient. I hope not to use httpget.abort() and instream.close() again.

public class ClientConnectionRelease {
    public static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.***.com");
            System.out.println("executing request " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                } catch (IOException ex) {
                    throw ex;
                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    try {
                        instream.close();
                    } catch (Exception ignore) {
                        // do something
                    }
                }
            }
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

1 Answers1

1

It doesn't appear that HttpGet supports the AutoClosable interface yet (Assuming you're using the Apache version, but you don't specify), but you can replace the second try block with a try-with-resources block:

try (InputStream instream = entity.getContent()) {
... //your read/process code here
} catch(IOException|RuntimeException ex) {
    throw ex
}
micker
  • 878
  • 6
  • 13
  • You are right it doesn't support `AutoClosable`, but how about this: http://stackoverflow.com/questions/21574478/what-is-the-difference-between-closeablehttpclient-and-httpclient-in-apache-http – csharpfolk Jun 09 '16 at 16:09
  • 1
    I'm using the apache version. What about HttpGet? Can I use like this: `try(CloseableHttpClient httpclient = HttpClients.createDefault()){ //do something with httpclient here }` – Vulcan Pong Jun 09 '16 at 16:18
  • @micker You are right. CloseableHttpClient impliments AutoCloseable. – Vulcan Pong Jun 09 '16 at 16:32