2016-06-09 2 views
0

Ich benutze HttpClient und habe einige Probleme damit. Ob ich die Entity erhalten möchte oder nicht, ich muss HttpGet und InputStream manuell freigeben. Gibt es eine Möglichkeit, Ressourcen in Java 7 für HttpClient automatisch freizugeben, z. B. "Try-with-resources"? Ich hoffe, nicht wieder httpget.abort() und intream.close() zu verwenden.HttpClient -wie Ressource in Java automatisch freigeben 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(); 
     } 
    } 
} 

Antwort

1

Es scheint nicht, dass HttpGet noch die AutoClosable Schnittstelle unterstützt (Vorausgesetzt, dass Sie die Apache-Version verwenden, aber nicht angeben), aber Sie können den zweiten try-Block mit einem ersetzen TRY mit-Ressourcen Block:

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

Sie haben Recht, es nicht 'AutoClosable' nicht unterstützt, aber wie wäre es damit: http://stackoverflow.com/questions/21574478/what-is-the-difference-between -closeablehttpclient-und-httpclient-in-apache-http – csharpfolk

+1

Ich benutze die Apache-Version. Was ist mit HttpGet? Kann ich das so verwenden: 'try (CloseableHttpClient httpclient = HttpClients.createDefault()) { // mach etwas mit httpclient hier }' –

+0

@VulcanPong Ich denke, du bist auf dem richtigen Weg – micker