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();
}
}
}