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();
}
}
}
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
Ich benutze die Apache-Version. Was ist mit HttpGet? Kann ich das so verwenden: 'try (CloseableHttpClient httpclient = HttpClients.createDefault()) { // mach etwas mit httpclient hier }' –
@VulcanPong Ich denke, du bist auf dem richtigen Weg – micker