HttpClient - 在Java 7中自动释放资源

时间:2016-06-09 15:54:16

标签: java httpclient

我使用HttpClient并遇到一些麻烦。无论我是否想要获取实体,我都需要手动释放HttpGet和InputStream。是否有任何方法可以自动释放资源,例如“尝试使用资源”#39;在Java 7中用于HttpClient。我希望不再使用httpget.abort()和instream.close()。

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 个答案:

答案 0 :(得分:1)

HttpGet似乎还不支持AutoClosable接口(假设您使用的是Apache版本,但未指定),但您可以使用 try-with-替换第二个try块资源块:

try (InputStream instream = entity.getContent()) {
... //your read/process code here
} catch(IOException|RuntimeException ex) {
    throw ex
}