diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java b/httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java index aeba60f46..6b6ba0e9b 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java @@ -40,28 +40,29 @@ public class ClientAbortMethod { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); + try { + HttpGet httpget = new HttpGet("http://www.apache.org/"); - HttpGet httpget = new HttpGet("http://www.apache.org/"); + System.out.println("executing request " + httpget.getURI()); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); - System.out.println("executing request " + httpget.getURI()); - HttpResponse response = httpclient.execute(httpget); - HttpEntity entity = response.getEntity(); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + System.out.println("----------------------------------------"); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + // Do not feel like reading the response body + // Call abort on the request object + httpget.abort(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - System.out.println("----------------------------------------"); - - // Do not feel like reading the response body - // Call abort on the request object - httpget.abort(); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java b/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java index f31fac53e..af7a7ebc8 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java @@ -41,27 +41,28 @@ public class ClientAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope("localhost", 443), + new UsernamePasswordCredentials("username", "password")); - httpclient.getCredentialsProvider().setCredentials( - new AuthScope("localhost", 443), - new UsernamePasswordCredentials("username", "password")); + HttpGet httpget = new HttpGet("https://localhost/protected"); - HttpGet httpget = new HttpGet("https://localhost/protected"); + System.out.println("executing request" + httpget.getRequestLine()); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); - System.out.println("executing request" + httpget.getRequestLine()); - HttpResponse response = httpclient.execute(httpget); - HttpEntity entity = response.getEntity(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + EntityUtils.consume(entity); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - EntityUtils.consume(entity); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java b/httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java index 4555d6661..49f111875 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java @@ -48,40 +48,41 @@ public class ClientChunkEncodedPost { System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); + try { + HttpPost httppost = new HttpPost("http://localhost:8080" + + "/servlets-examples/servlet/RequestInfoExample"); - HttpPost httppost = new HttpPost("http://localhost:8080" + - "/servlets-examples/servlet/RequestInfoExample"); + File file = new File(args[0]); - File file = new File(args[0]); + InputStreamEntity reqEntity = new InputStreamEntity( + new FileInputStream(file), -1); + reqEntity.setContentType("binary/octet-stream"); + reqEntity.setChunked(true); + // It may be more appropriate to use FileEntity class in this particular + // instance but we are using a more generic InputStreamEntity to demonstrate + // the capability to stream out data from any arbitrary source + // + // FileEntity entity = new FileEntity(file, "binary/octet-stream"); - InputStreamEntity reqEntity = new InputStreamEntity( - new FileInputStream(file), -1); - reqEntity.setContentType("binary/octet-stream"); - reqEntity.setChunked(true); - // It may be more appropriate to use FileEntity class in this particular - // instance but we are using a more generic InputStreamEntity to demonstrate - // the capability to stream out data from any arbitrary source - // - // FileEntity entity = new FileEntity(file, "binary/octet-stream"); + httppost.setEntity(reqEntity); - httppost.setEntity(reqEntity); + System.out.println("executing request " + httppost.getRequestLine()); + HttpResponse response = httpclient.execute(httppost); + HttpEntity resEntity = response.getEntity(); - System.out.println("executing request " + httppost.getRequestLine()); - HttpResponse response = httpclient.execute(httppost); - HttpEntity resEntity = response.getEntity(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (resEntity != null) { - System.out.println("Response content length: " + resEntity.getContentLength()); - System.out.println("Chunked?: " + resEntity.isChunked()); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (resEntity != null) { + System.out.println("Response content length: " + resEntity.getContentLength()); + System.out.println("Chunked?: " + resEntity.isChunked()); + } + EntityUtils.consume(resEntity); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - EntityUtils.consume(resEntity); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java b/httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java index 69217c2bb..69299378b 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java @@ -44,48 +44,49 @@ public class ClientConnectionRelease { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); + try { + HttpGet httpget = new HttpGet("http://www.apache.org/"); - HttpGet httpget = new HttpGet("http://www.apache.org/"); + // Execute HTTP request + System.out.println("executing request " + httpget.getURI()); + HttpResponse response = httpclient.execute(httpget); - // Execute HTTP request - System.out.println("executing request " + httpget.getURI()); - HttpResponse response = httpclient.execute(httpget); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + System.out.println("----------------------------------------"); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - System.out.println("----------------------------------------"); - - // Get hold of the response entity - HttpEntity entity = response.getEntity(); - - // If the response does not enclose an entity, there is no need - // to bother about connection release - if (entity != null) { - InputStream instream = entity.getContent(); - try { - instream.read(); - // do something useful with the response - } catch (IOException ex) { - // In case of an IOException the connection will be released - // back to the connection manager automatically - throw ex; - } catch (RuntimeException ex) { - // In case of an unexpected exception you may want to abort - // the HTTP request in order to shut down the underlying - // connection immediately. - httpget.abort(); - throw ex; - } finally { - // Closing the input stream will trigger connection release - instream.close(); + // Get hold of the response entity + HttpEntity entity = response.getEntity(); + // If the response does not enclose an entity, there is no need + // to bother about connection release + if (entity != null) { + InputStream instream = entity.getContent(); + try { + instream.read(); + // do something useful with the response + } catch (IOException ex) { + // In case of an IOException the connection will be released + // back to the connection manager automatically + throw ex; + } catch (RuntimeException ex) { + // In case of an unexpected exception you may want to abort + // the HTTP request in order to shut down the underlying + // connection immediately. + httpget.abort(); + throw ex; + } finally { + // Closing the input stream will trigger connection release + try { instream.close(); } catch (Exception ignore) {} + } } - } - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java b/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java index f13d31898..957a6f706 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java @@ -52,42 +52,44 @@ public class ClientCustomContext { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); + try { + // Create a local instance of cookie store + CookieStore cookieStore = new BasicCookieStore(); - // Create a local instance of cookie store - CookieStore cookieStore = new BasicCookieStore(); + // Create local HTTP context + HttpContext localContext = new BasicHttpContext(); + // Bind custom cookie store to the local context + localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); - // Create local HTTP context - HttpContext localContext = new BasicHttpContext(); - // Bind custom cookie store to the local context - localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); + HttpGet httpget = new HttpGet("http://www.google.com/"); - HttpGet httpget = new HttpGet("http://www.google.com/"); + System.out.println("executing request " + httpget.getURI()); - System.out.println("executing request " + httpget.getURI()); + // Pass local context as a parameter + HttpResponse response = httpclient.execute(httpget, localContext); + HttpEntity entity = response.getEntity(); - // Pass local context as a parameter - HttpResponse response = httpclient.execute(httpget, localContext); - HttpEntity entity = response.getEntity(); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + List cookies = cookieStore.getCookies(); + for (int i = 0; i < cookies.size(); i++) { + System.out.println("Local cookie: " + cookies.get(i)); + } - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + // Consume response content + EntityUtils.consume(entity); + + System.out.println("----------------------------------------"); + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - List cookies = cookieStore.getCookies(); - for (int i = 0; i < cookies.size(); i++) { - System.out.println("Local cookie: " + cookies.get(i)); - } - - // Consume response content - EntityUtils.consume(entity); - - System.out.println("----------------------------------------"); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java b/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java index d5cea4e27..da5df2e08 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java @@ -46,37 +46,39 @@ public class ClientCustomSSL { public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); - - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - FileInputStream instream = new FileInputStream(new File("my.keystore")); try { - trustStore.load(instream, "nopassword".toCharArray()); + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + FileInputStream instream = new FileInputStream(new File("my.keystore")); + try { + trustStore.load(instream, "nopassword".toCharArray()); + } finally { + try { instream.close(); } catch (Exception ignore) {} + } + + SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); + Scheme sch = new Scheme("https", 443, socketFactory); + httpclient.getConnectionManager().getSchemeRegistry().register(sch); + + HttpGet httpget = new HttpGet("https://localhost/"); + + System.out.println("executing request" + httpget.getRequestLine()); + + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + EntityUtils.consume(entity); + } finally { - instream.close(); + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - - SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); - Scheme sch = new Scheme("https", 443, socketFactory); - httpclient.getConnectionManager().getSchemeRegistry().register(sch); - - HttpGet httpget = new HttpGet("https://localhost/"); - - System.out.println("executing request" + httpget.getRequestLine()); - - HttpResponse response = httpclient.execute(httpget); - HttpEntity entity = response.getEntity(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - } - EntityUtils.consume(entity); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java b/httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java index 5d934b158..85cb149e2 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java @@ -48,48 +48,50 @@ public class ClientEvictExpiredConnections { cm.setMaxTotal(100); HttpClient httpclient = new DefaultHttpClient(cm); + try { + // create an array of URIs to perform GETs on + String[] urisToGet = { + "http://jakarta.apache.org/", + "http://jakarta.apache.org/commons/", + "http://jakarta.apache.org/commons/httpclient/", + "http://svn.apache.org/viewvc/jakarta/httpcomponents/" + }; - // create an array of URIs to perform GETs on - String[] urisToGet = { - "http://jakarta.apache.org/", - "http://jakarta.apache.org/commons/", - "http://jakarta.apache.org/commons/httpclient/", - "http://svn.apache.org/viewvc/jakarta/httpcomponents/" - }; + IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); + connEvictor.start(); - IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); - connEvictor.start(); + for (int i = 0; i < urisToGet.length; i++) { + String requestURI = urisToGet[i]; + HttpGet req = new HttpGet(requestURI); - for (int i = 0; i < urisToGet.length; i++) { - String requestURI = urisToGet[i]; - HttpGet req = new HttpGet(requestURI); + System.out.println("executing request " + requestURI); - System.out.println("executing request " + requestURI); + HttpResponse rsp = httpclient.execute(req); + HttpEntity entity = rsp.getEntity(); - HttpResponse rsp = httpclient.execute(req); - HttpEntity entity = rsp.getEntity(); + System.out.println("----------------------------------------"); + System.out.println(rsp.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + System.out.println("----------------------------------------"); - System.out.println("----------------------------------------"); - System.out.println(rsp.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + EntityUtils.consume(entity); } - System.out.println("----------------------------------------"); - EntityUtils.consume(entity); + // Sleep 10 sec and let the connection evictor do its job + Thread.sleep(20000); + + // Shut down the evictor thread + connEvictor.shutdown(); + connEvictor.join(); + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - - // Sleep 10 sec and let the connection evictor do its job - Thread.sleep(20000); - - // Shut down the evictor thread - connEvictor.shutdown(); - connEvictor.join(); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } public static class IdleConnectionEvictor extends Thread { diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java b/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java index fd3d97ba1..970fd9443 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java @@ -45,31 +45,33 @@ public class ClientExecuteDirect { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + HttpHost target = new HttpHost("www.apache.org", 80, "http"); + HttpGet req = new HttpGet("/"); - HttpHost target = new HttpHost("www.apache.org", 80, "http"); - HttpGet req = new HttpGet("/"); + System.out.println("executing request to " + target); - System.out.println("executing request to " + target); + HttpResponse rsp = httpclient.execute(target, req); + HttpEntity entity = rsp.getEntity(); - HttpResponse rsp = httpclient.execute(target, req); - HttpEntity entity = rsp.getEntity(); + System.out.println("----------------------------------------"); + System.out.println(rsp.getStatusLine()); + Header[] headers = rsp.getAllHeaders(); + for (int i = 0; i < headers.length; i++) { + System.out.println(headers[i]); + } + System.out.println("----------------------------------------"); - System.out.println("----------------------------------------"); - System.out.println(rsp.getStatusLine()); - Header[] headers = rsp.getAllHeaders(); - for (int i = 0; i < headers.length; i++) { - System.out.println(headers[i]); + if (entity != null) { + System.out.println(EntityUtils.toString(entity)); + } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - System.out.println("----------------------------------------"); - - if (entity != null) { - System.out.println(EntityUtils.toString(entity)); - } - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java b/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java index 2cb908ad9..0711b45cd 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java @@ -48,31 +48,34 @@ public class ClientExecuteProxy { HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); - httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); + try { + httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); - HttpHost target = new HttpHost("issues.apache.org", 443, "https"); - HttpGet req = new HttpGet("/"); + HttpHost target = new HttpHost("issues.apache.org", 443, "https"); + HttpGet req = new HttpGet("/"); - System.out.println("executing request to " + target + " via " + proxy); - HttpResponse rsp = httpclient.execute(target, req); - HttpEntity entity = rsp.getEntity(); + System.out.println("executing request to " + target + " via " + proxy); + HttpResponse rsp = httpclient.execute(target, req); + HttpEntity entity = rsp.getEntity(); - System.out.println("----------------------------------------"); - System.out.println(rsp.getStatusLine()); - Header[] headers = rsp.getAllHeaders(); - for (int i = 0; i cookies = httpclient.getCookieStore().getCookies(); - if (cookies.isEmpty()) { - System.out.println("None"); - } else { - for (int i = 0; i < cookies.size(); i++) { - System.out.println("- " + cookies.get(i).toString()); + System.out.println("Initial set of cookies:"); + List cookies = httpclient.getCookieStore().getCookies(); + if (cookies.isEmpty()) { + System.out.println("None"); + } else { + for (int i = 0; i < cookies.size(); i++) { + System.out.println("- " + cookies.get(i).toString()); + } } - } - HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + - "org=self_registered_users&" + - "goto=/portal/dt&" + - "gotoOnFail=/portal/dt?error=true"); + HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + + "org=self_registered_users&" + + "goto=/portal/dt&" + + "gotoOnFail=/portal/dt?error=true"); - List nvps = new ArrayList (); - nvps.add(new BasicNameValuePair("IDToken1", "username")); - nvps.add(new BasicNameValuePair("IDToken2", "password")); + List nvps = new ArrayList (); + nvps.add(new BasicNameValuePair("IDToken1", "username")); + nvps.add(new BasicNameValuePair("IDToken2", "password")); - httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); + httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); - response = httpclient.execute(httpost); - entity = response.getEntity(); + response = httpclient.execute(httpost); + entity = response.getEntity(); - System.out.println("Login form get: " + response.getStatusLine()); - EntityUtils.consume(entity); + System.out.println("Login form get: " + response.getStatusLine()); + EntityUtils.consume(entity); - System.out.println("Post logon cookies:"); - cookies = httpclient.getCookieStore().getCookies(); - if (cookies.isEmpty()) { - System.out.println("None"); - } else { - for (int i = 0; i < cookies.size(); i++) { - System.out.println("- " + cookies.get(i).toString()); + System.out.println("Post logon cookies:"); + cookies = httpclient.getCookieStore().getCookies(); + if (cookies.isEmpty()) { + System.out.println("None"); + } else { + for (int i = 0; i < cookies.size(); i++) { + System.out.println("- " + cookies.get(i).toString()); + } } - } - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java b/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java index 7399fed01..0f6844eb6 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java @@ -62,65 +62,67 @@ public class ClientGZipContentCompression { public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + httpclient.addRequestInterceptor(new HttpRequestInterceptor() { - httpclient.addRequestInterceptor(new HttpRequestInterceptor() { - - public void process( - final HttpRequest request, - final HttpContext context) throws HttpException, IOException { - if (!request.containsHeader("Accept-Encoding")) { - request.addHeader("Accept-Encoding", "gzip"); + public void process( + final HttpRequest request, + final HttpContext context) throws HttpException, IOException { + if (!request.containsHeader("Accept-Encoding")) { + request.addHeader("Accept-Encoding", "gzip"); + } } - } - }); + }); - httpclient.addResponseInterceptor(new HttpResponseInterceptor() { + httpclient.addResponseInterceptor(new HttpResponseInterceptor() { - public void process( - final HttpResponse response, - final HttpContext context) throws HttpException, IOException { - HttpEntity entity = response.getEntity(); - Header ceheader = entity.getContentEncoding(); - if (ceheader != null) { - HeaderElement[] codecs = ceheader.getElements(); - for (int i = 0; i < codecs.length; i++) { - if (codecs[i].getName().equalsIgnoreCase("gzip")) { - response.setEntity( - new GzipDecompressingEntity(response.getEntity())); - return; + public void process( + final HttpResponse response, + final HttpContext context) throws HttpException, IOException { + HttpEntity entity = response.getEntity(); + Header ceheader = entity.getContentEncoding(); + if (ceheader != null) { + HeaderElement[] codecs = ceheader.getElements(); + for (int i = 0; i < codecs.length; i++) { + if (codecs[i].getName().equalsIgnoreCase("gzip")) { + response.setEntity( + new GzipDecompressingEntity(response.getEntity())); + return; + } } } } + + }); + + HttpGet httpget = new HttpGet("http://www.apache.org/"); + + // Execute HTTP request + System.out.println("executing request " + httpget.getURI()); + HttpResponse response = httpclient.execute(httpget); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + System.out.println(response.getLastHeader("Content-Encoding")); + System.out.println(response.getLastHeader("Content-Length")); + System.out.println("----------------------------------------"); + + HttpEntity entity = response.getEntity(); + + if (entity != null) { + String content = EntityUtils.toString(entity); + System.out.println(content); + System.out.println("----------------------------------------"); + System.out.println("Uncompressed size: "+content.length()); } - }); - - HttpGet httpget = new HttpGet("http://www.apache.org/"); - - // Execute HTTP request - System.out.println("executing request " + httpget.getURI()); - HttpResponse response = httpclient.execute(httpget); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - System.out.println(response.getLastHeader("Content-Encoding")); - System.out.println(response.getLastHeader("Content-Length")); - System.out.println("----------------------------------------"); - - HttpEntity entity = response.getEntity(); - - if (entity != null) { - String content = EntityUtils.toString(entity); - System.out.println(content); - System.out.println("----------------------------------------"); - System.out.println("Uncompressed size: "+content.length()); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } static class GzipDecompressingEntity extends HttpEntityWrapper { diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java b/httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java index a2e501e24..5294e263e 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java @@ -50,66 +50,68 @@ public class ClientInteractiveAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + // Create local execution context + HttpContext localContext = new BasicHttpContext(); - // Create local execution context - HttpContext localContext = new BasicHttpContext(); + HttpGet httpget = new HttpGet("http://localhost/test"); - HttpGet httpget = new HttpGet("http://localhost/test"); + boolean trying = true; + while (trying) { + System.out.println("executing request " + httpget.getRequestLine()); + HttpResponse response = httpclient.execute(httpget, localContext); - boolean trying = true; - while (trying) { - System.out.println("executing request " + httpget.getRequestLine()); - HttpResponse response = httpclient.execute(httpget, localContext); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - - // Consume response content - HttpEntity entity = response.getEntity(); - EntityUtils.consume(entity); - - int sc = response.getStatusLine().getStatusCode(); - - AuthState authState = null; - if (sc == HttpStatus.SC_UNAUTHORIZED) { - // Target host authentication required - authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); - } - if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { - // Proxy authentication required - authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); - } - - if (authState != null) { System.out.println("----------------------------------------"); - AuthScope authScope = authState.getAuthScope(); - System.out.println("Please provide credentials"); - System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort()); - System.out.println(" Realm: " + authScope.getRealm()); + System.out.println(response.getStatusLine()); + + // Consume response content + HttpEntity entity = response.getEntity(); + EntityUtils.consume(entity); + + int sc = response.getStatusLine().getStatusCode(); + + AuthState authState = null; + if (sc == HttpStatus.SC_UNAUTHORIZED) { + // Target host authentication required + authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); + } + if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { + // Proxy authentication required + authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); + } + + if (authState != null) { + System.out.println("----------------------------------------"); + AuthScope authScope = authState.getAuthScope(); + System.out.println("Please provide credentials"); + System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort()); + System.out.println(" Realm: " + authScope.getRealm()); - BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); - System.out.print("Enter username: "); - String user = console.readLine(); - System.out.print("Enter password: "); - String password = console.readLine(); + System.out.print("Enter username: "); + String user = console.readLine(); + System.out.print("Enter password: "); + String password = console.readLine(); - if (user != null && user.length() > 0) { - Credentials creds = new UsernamePasswordCredentials(user, password); - httpclient.getCredentialsProvider().setCredentials(authScope, creds); - trying = true; + if (user != null && user.length() > 0) { + Credentials creds = new UsernamePasswordCredentials(user, password); + httpclient.getCredentialsProvider().setCredentials(authScope, creds); + trying = true; + } else { + trying = false; + } } else { trying = false; } - } else { - trying = false; } - } - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientKerberosAuthentication.java b/httpclient/src/examples/org/apache/http/examples/client/ClientKerberosAuthentication.java index a2bcd7b10..4ce0820cc 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientKerberosAuthentication.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientKerberosAuthentication.java @@ -126,48 +126,50 @@ public class ClientKerberosAuthentication { System.setProperty("javax.security.auth.useSubjectCredsOnly","false"); DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + NegotiateSchemeFactory nsf = new NegotiateSchemeFactory(); +// nsf.setStripPort(false); +// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator()); - NegotiateSchemeFactory nsf = new NegotiateSchemeFactory(); -// nsf.setStripPort(false); -// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator()); + httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf); - httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf); + Credentials use_jaas_creds = new Credentials() { - Credentials use_jaas_creds = new Credentials() { + public String getPassword() { + return null; + } - public String getPassword() { - return null; + public Principal getUserPrincipal() { + return null; + } + + }; + + httpclient.getCredentialsProvider().setCredentials( + new AuthScope(null, -1, null), + use_jaas_creds); + + HttpUriRequest request = new HttpGet("http://kerberoshost/"); + HttpResponse response = httpclient.execute(request); + HttpEntity entity = response.getEntity(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + System.out.println("----------------------------------------"); + if (entity != null) { + System.out.println(EntityUtils.toString(entity)); } + System.out.println("----------------------------------------"); - public Principal getUserPrincipal() { - return null; - } + // This ensures the connection gets released back to the manager + EntityUtils.consume(entity); - }; - - httpclient.getCredentialsProvider().setCredentials( - new AuthScope(null, -1, null), - use_jaas_creds); - - HttpUriRequest request = new HttpGet("http://kerberoshost/"); - HttpResponse response = httpclient.execute(request); - HttpEntity entity = response.getEntity(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - System.out.println("----------------------------------------"); - if (entity != null) { - System.out.println(EntityUtils.toString(entity)); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - System.out.println("----------------------------------------"); - - // This ensures the connection gets released back to the manager - EntityUtils.consume(entity); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java b/httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java index 52a6dbd80..db6cd7045 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java @@ -49,37 +49,39 @@ public class ClientMultiThreadedExecution { ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); cm.setMaxTotal(100); - HttpClient httpClient = new DefaultHttpClient(cm); + HttpClient httpclient = new DefaultHttpClient(cm); + try { + // create an array of URIs to perform GETs on + String[] urisToGet = { + "http://hc.apache.org/", + "http://hc.apache.org/httpcomponents-core-ga/", + "http://hc.apache.org/httpcomponents-client-ga/", + "http://svn.apache.org/viewvc/httpcomponents/" + }; - // create an array of URIs to perform GETs on - String[] urisToGet = { - "http://hc.apache.org/", - "http://hc.apache.org/httpcomponents-core-ga/", - "http://hc.apache.org/httpcomponents-client-ga/", - "http://svn.apache.org/viewvc/httpcomponents/" - }; + // create a thread for each URI + GetThread[] threads = new GetThread[urisToGet.length]; + for (int i = 0; i < threads.length; i++) { + HttpGet httpget = new HttpGet(urisToGet[i]); + threads[i] = new GetThread(httpclient, httpget, i + 1); + } - // create a thread for each URI - GetThread[] threads = new GetThread[urisToGet.length]; - for (int i = 0; i < threads.length; i++) { - HttpGet httpget = new HttpGet(urisToGet[i]); - threads[i] = new GetThread(httpClient, httpget, i + 1); + // start the threads + for (int j = 0; j < threads.length; j++) { + threads[j].start(); + } + + // join the threads + for (int j = 0; j < threads.length; j++) { + threads[j].join(); + } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - - // start the threads - for (int j = 0; j < threads.length; j++) { - threads[j].start(); - } - - // join the threads - for (int j = 0; j < threads.length; j++) { - threads[j].join(); - } - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpClient.getConnectionManager().shutdown(); } /** diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java b/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java index 28818ceec..30e12d8b0 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java @@ -54,43 +54,45 @@ public class ClientPreemptiveBasicAuthentication { HttpHost targetHost = new HttpHost("localhost", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope(targetHost.getHostName(), targetHost.getPort()), + new UsernamePasswordCredentials("username", "password")); - httpclient.getCredentialsProvider().setCredentials( - new AuthScope(targetHost.getHostName(), targetHost.getPort()), - new UsernamePasswordCredentials("username", "password")); + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + // Generate BASIC scheme object and add it to the local + // auth cache + BasicScheme basicAuth = new BasicScheme(); + authCache.put(targetHost, basicAuth); - // Create AuthCache instance - AuthCache authCache = new BasicAuthCache(); - // Generate BASIC scheme object and add it to the local - // auth cache - BasicScheme basicAuth = new BasicScheme(); - authCache.put(targetHost, basicAuth); + // Add AuthCache to the execution context + BasicHttpContext localcontext = new BasicHttpContext(); + localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); - // Add AuthCache to the execution context - BasicHttpContext localcontext = new BasicHttpContext(); - localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); + HttpGet httpget = new HttpGet("/"); - HttpGet httpget = new HttpGet("/"); + System.out.println("executing request: " + httpget.getRequestLine()); + System.out.println("to target: " + targetHost); - System.out.println("executing request: " + httpget.getRequestLine()); - System.out.println("to target: " + targetHost); + for (int i = 0; i < 3; i++) { + HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); + HttpEntity entity = response.getEntity(); - for (int i = 0; i < 3; i++) { - HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); - HttpEntity entity = response.getEntity(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + EntityUtils.consume(entity); } - EntityUtils.consume(entity); - } - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java b/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java index bd997486d..be71f467f 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java @@ -54,47 +54,49 @@ public class ClientPreemptiveDigestAuthentication { HttpHost targetHost = new HttpHost("localhost", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope(targetHost.getHostName(), targetHost.getPort()), + new UsernamePasswordCredentials("username", "password")); - httpclient.getCredentialsProvider().setCredentials( - new AuthScope(targetHost.getHostName(), targetHost.getPort()), - new UsernamePasswordCredentials("username", "password")); + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + // Generate DIGEST scheme object, initialize it and add it to the local + // auth cache + DigestScheme digestAuth = new DigestScheme(); + // Suppose we already know the realm name + digestAuth.overrideParamter("realm", "some realm"); + // Suppose we already know the expected nonce value + digestAuth.overrideParamter("nonce", "whatever"); + authCache.put(targetHost, digestAuth); - // Create AuthCache instance - AuthCache authCache = new BasicAuthCache(); - // Generate DIGEST scheme object, initialize it and add it to the local - // auth cache - DigestScheme digestAuth = new DigestScheme(); - // Suppose we already know the realm name - digestAuth.overrideParamter("realm", "some realm"); - // Suppose we already know the expected nonce value - digestAuth.overrideParamter("nonce", "whatever"); - authCache.put(targetHost, digestAuth); + // Add AuthCache to the execution context + BasicHttpContext localcontext = new BasicHttpContext(); + localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); - // Add AuthCache to the execution context - BasicHttpContext localcontext = new BasicHttpContext(); - localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); + HttpGet httpget = new HttpGet("/"); - HttpGet httpget = new HttpGet("/"); + System.out.println("executing request: " + httpget.getRequestLine()); + System.out.println("to target: " + targetHost); - System.out.println("executing request: " + httpget.getRequestLine()); - System.out.println("to target: " + targetHost); + for (int i = 0; i < 3; i++) { + HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); + HttpEntity entity = response.getEntity(); - for (int i = 0; i < 3; i++) { - HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); - HttpEntity entity = response.getEntity(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + EntityUtils.consume(entity); } - EntityUtils.consume(entity); - } - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java b/httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java index 15190ec1b..b8f6c82ce 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java @@ -44,35 +44,37 @@ public class ClientProxyAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope("localhost", 8080), + new UsernamePasswordCredentials("username", "password")); - httpclient.getCredentialsProvider().setCredentials( - new AuthScope("localhost", 8080), - new UsernamePasswordCredentials("username", "password")); + HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https"); + HttpHost proxy = new HttpHost("localhost", 8080); - HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https"); - HttpHost proxy = new HttpHost("localhost", 8080); + httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); - httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); + HttpGet httpget = new HttpGet("/"); - HttpGet httpget = new HttpGet("/"); + System.out.println("executing request: " + httpget.getRequestLine()); + System.out.println("via proxy: " + proxy); + System.out.println("to target: " + targetHost); - System.out.println("executing request: " + httpget.getRequestLine()); - System.out.println("via proxy: " + proxy); - System.out.println("to target: " + targetHost); + HttpResponse response = httpclient.execute(targetHost, httpget); + HttpEntity entity = response.getEntity(); - HttpResponse response = httpclient.execute(targetHost, httpget); - HttpEntity entity = response.getEntity(); + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + EntityUtils.consume(entity); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); } - EntityUtils.consume(entity); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } diff --git a/httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java b/httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java index eabf3f39d..bf77eec52 100644 --- a/httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java +++ b/httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java @@ -42,22 +42,24 @@ public class ClientWithResponseHandler { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); + try { + HttpGet httpget = new HttpGet("http://www.google.com/"); - HttpGet httpget = new HttpGet("http://www.google.com/"); + System.out.println("executing request " + httpget.getURI()); - System.out.println("executing request " + httpget.getURI()); + // Create a response handler + ResponseHandler responseHandler = new BasicResponseHandler(); + String responseBody = httpclient.execute(httpget, responseHandler); + System.out.println("----------------------------------------"); + System.out.println(responseBody); + System.out.println("----------------------------------------"); - // Create a response handler - ResponseHandler responseHandler = new BasicResponseHandler(); - String responseBody = httpclient.execute(httpget, responseHandler); - System.out.println("----------------------------------------"); - System.out.println(responseBody); - System.out.println("----------------------------------------"); - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } } } diff --git a/httpmime/src/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java b/httpmime/src/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java index fab7546e8..77e002eae 100644 --- a/httpmime/src/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java +++ b/httpmime/src/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java @@ -49,29 +49,32 @@ public class ClientMultipartFormPost { System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); + try { + HttpPost httppost = new HttpPost("http://localhost:8080" + + "/servlets-examples/servlet/RequestInfoExample"); - HttpPost httppost = new HttpPost("http://localhost:8080" + - "/servlets-examples/servlet/RequestInfoExample"); + FileBody bin = new FileBody(new File(args[0])); + StringBody comment = new StringBody("A binary file of some kind"); - FileBody bin = new FileBody(new File(args[0])); - StringBody comment = new StringBody("A binary file of some kind"); + MultipartEntity reqEntity = new MultipartEntity(); + reqEntity.addPart("bin", bin); + reqEntity.addPart("comment", comment); - MultipartEntity reqEntity = new MultipartEntity(); - reqEntity.addPart("bin", bin); - reqEntity.addPart("comment", comment); - - httppost.setEntity(reqEntity); - - System.out.println("executing request " + httppost.getRequestLine()); - HttpResponse response = httpclient.execute(httppost); - HttpEntity resEntity = response.getEntity(); + httppost.setEntity(reqEntity); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (resEntity != null) { - System.out.println("Response content length: " + resEntity.getContentLength()); + System.out.println("executing request " + httppost.getRequestLine()); + HttpResponse response = httpclient.execute(httppost); + HttpEntity resEntity = response.getEntity(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (resEntity != null) { + System.out.println("Response content length: " + resEntity.getContentLength()); + } + EntityUtils.consume(resEntity); + } finally { + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } - EntityUtils.consume(resEntity); } }