2016-06-09 32 views
0

我使用HttpClient并且遇到了一些麻烦。无论我是否想要获取实体,我都需要手动发布HttpGet和InputStream。是否有任何方法可以自动释放资源,如Java 7中的“try-with-resources”for HttpClient。我希望不要再使用httpget.abort()和instream.close()。HttpClient - 如何在Java 7中自动释放资源

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

它不会出现HTTPGET支持AutoClosable接口,但(假设你正在使用Apache的版本,但你不指定),但你可以替换为第二try块试戴与资源块:

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

你是对的,不支持'AutoClosable',但这个怎么样:http://stackoverflow.com/questions/21574478/what-is-the-difference-between -closeablehttpclient-and-httpclient-in-apache-http – csharpfolk

+1

我正在使用apache版本。那么HttpGet呢?我可以这样使用:'尝试(CloseableHttpClient httpclient = HttpClients.createDefault()){ //用httpclient在这里做一些事情 }' –

+0

@VulcanPong我认为你在正确的轨道上 – micker