--- httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java 2010-11-30 11:29:03.000000000 +0000 @@ -40,28 +40,30 @@ 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("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); + 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("----------------------------------------"); + + // 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } - 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(); } } --- httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java 2010-11-30 11:29:22.000000000 +0000 @@ -37,35 +37,37 @@ /** * A simple example that uses HttpClient to execute an HTTP request against - * a target site that requires user authentication. + * a target site that requires user authentication. */ 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"); - - 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()); - } - if (entity != null) { - entity.consumeContent(); - } + HttpGet httpget = new HttpGet("https://localhost/protected"); + + System.out.println("executing request" + httpget.getRequestLine()); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); - // 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("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + if (entity != null) { + entity.consumeContent(); + } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } } --- httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java 2010-11-30 11:29:40.000000000 +0000 @@ -21,7 +21,7 @@ * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . - * + * */ package org.apache.http.examples.client; @@ -47,42 +47,44 @@ System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); - - HttpPost httppost = new HttpPost("http://localhost:8080" + - "/servlets-examples/servlet/RequestInfoExample"); - - 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"); - - httppost.setEntity(reqEntity); - - 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()); + try { + HttpPost httppost = new HttpPost("http://localhost:8080" + + "/servlets-examples/servlet/RequestInfoExample"); + + 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"); + + httppost.setEntity(reqEntity); + + 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()); + } + if (resEntity != null) { + resEntity.consumeContent(); + } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } - if (resEntity != null) { - resEntity.consumeContent(); - } - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } - + } --- httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java 2010-11-30 11:29:57.000000000 +0000 @@ -38,63 +38,65 @@ import org.apache.http.impl.client.DefaultHttpClient; /** - * This example demonstrates the recommended way of using API to make sure + * This example demonstrates the recommended way of using API to make sure * the underlying connection gets released back to the connection manager. */ 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("----------------------------------------"); - - // 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) { - BufferedReader reader = new BufferedReader( - new InputStreamReader(entity.getContent())); - try { - - // do something useful with the response - System.out.println(reader.readLine()); - - } 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 and release it back to the connection manager. - httpget.abort(); - throw ex; - - } finally { - - // Closing the input stream will trigger connection release - reader.close(); - + 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) { + BufferedReader reader = new BufferedReader( + new InputStreamReader(entity.getContent())); + try { + + // do something useful with the response + System.out.println(reader.readLine()); + + } 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 and release it back to the connection manager. + httpget.abort(); + throw ex; + + } finally { + + // Closing the input stream will trigger connection release + reader.close(); + + } } - } - // 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } } --- httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java 2010-11-30 11:30:13.000000000 +0000 @@ -38,58 +38,60 @@ import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; /** - * This example demonstrates the use of a local HTTP context populated with + * This example demonstrates the use of a local HTTP context populated with * custom attributes. */ public class ClientCustomContext { public final static void main(String[] args) throws Exception { - - HttpClient httpclient = new DefaultHttpClient(); - // 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); - - HttpGet httpget = new HttpGet("http://www.google.com/"); - - System.out.println("executing request " + httpget.getURI()); - - // 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)); - } - - // Consume response content - if (entity != null) { - entity.consumeContent(); + HttpClient httpclient = new DefaultHttpClient(); + try { + // 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); + + HttpGet httpget = new HttpGet("http://www.google.com/"); + + System.out.println("executing request " + httpget.getURI()); + + // 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)); + } + + // Consume response content + if (entity != null) { + entity.consumeContent(); + } + + System.out.println("----------------------------------------"); + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } - - 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(); } - + } --- httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java 2010-11-30 11:28:35.000000000 +0000 @@ -45,39 +45,41 @@ 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 { + instream.close(); + } + + SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); + Scheme sch = new Scheme("https", socketFactory, 443); + 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()); + } + if (entity != null) { + entity.consumeContent(); + } + } finally { - instream.close(); - } - - SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); - Scheme sch = new Scheme("https", socketFactory, 443); - 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()); + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } - if (entity != null) { - entity.consumeContent(); - } - - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpclient.getConnectionManager().shutdown(); } } --- httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java 2010-11-30 11:20:30.000000000 +0000 @@ -23,7 +23,7 @@ * . * */ - + package org.apache.http.examples.client; import java.util.concurrent.TimeUnit; @@ -55,66 +55,68 @@ HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - - // Create and initialize scheme registry + + // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - + ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); HttpClient httpclient = new DefaultHttpClient(cm, params); - - // 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(); - - for (int i = 0; i < urisToGet.length; i++) { - String requestURI = urisToGet[i]; - HttpGet req = new HttpGet(requestURI); - - System.out.println("executing request " + requestURI); - - 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("----------------------------------------"); + 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/" + }; + + IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); + connEvictor.start(); + + for (int i = 0; i < urisToGet.length; i++) { + String requestURI = urisToGet[i]; + HttpGet req = new HttpGet(requestURI); + + System.out.println("executing request " + requestURI); + + 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("----------------------------------------"); - if (entity != null) { - entity.consumeContent(); + if (entity != null) { + entity.consumeContent(); + } } + + // 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } - - // 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 { - + private final ClientConnectionManager connMgr; - + private volatile boolean shutdown; - + public IdleConnectionEvictor(ClientConnectionManager connMgr) { super(); this.connMgr = connMgr; @@ -137,14 +139,14 @@ // terminate } } - + public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } - + } - + } --- httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java 2010-11-30 11:19:38.000000000 +0000 @@ -47,7 +47,7 @@ /** * How to send a request directly using {@link HttpClient}. - * + * * @since 4.0 */ public class ClientExecuteDirect { @@ -61,7 +61,7 @@ // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. - supportedSchemes.register(new Scheme("http", + supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // prepare parameters @@ -70,33 +70,35 @@ HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); - ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, + ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, supportedSchemes); DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params); + try { + HttpGet req = new HttpGet("/"); - 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("----------------------------------------"); - - if (entity != null) { - System.out.println(EntityUtils.toString(entity)); + 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("----------------------------------------"); + + 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 + try { httpclient.getConnectionManager().shutdown(); } 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(); } } --- httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java 2010-11-30 11:22:05.000000000 +0000 @@ -65,9 +65,9 @@ // Register the "http" and "https" protocol schemes, they are // required by the default operator to look up socket factories. - supportedSchemes.register(new Scheme("http", + supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - supportedSchemes.register(new Scheme("https", + supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // prepare parameters @@ -76,35 +76,37 @@ HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params); + try { + httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); - httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); + HttpGet req = new HttpGet("/"); - 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("----------------------------------------"); - 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("Login form get: " + response.getStatusLine()); + if (entity != null) { + entity.consumeContent(); + } + 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"); - - List nvps = new ArrayList (); - nvps.add(new BasicNameValuePair("IDToken1", "username")); - nvps.add(new BasicNameValuePair("IDToken2", "password")); - - httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); - - response = httpclient.execute(httpost); - entity = response.getEntity(); - - System.out.println("Login form get: " + response.getStatusLine()); - if (entity != null) { - entity.consumeContent(); - } + 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")); + + httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); + + response = httpclient.execute(httpost); + entity = response.getEntity(); + + System.out.println("Login form get: " + response.getStatusLine()); + if (entity != null) { + entity.consumeContent(); + } - 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } } --- httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java 2010-11-30 11:23:29.000000000 +0000 @@ -46,15 +46,15 @@ import org.apache.http.util.EntityUtils; /** - * Demonstration of the use of protocol interceptors to transparently + * Demonstration of the use of protocol interceptors to transparently * modify properties of HTTP messages sent / received by the HTTP client. *

- * In this particular case HTTP client is made capable of transparent content + * In this particular case HTTP client is made capable of transparent content * GZIP compression by adding two protocol interceptors: a request interceptor * that adds 'Accept-Encoding: gzip' header to all outgoing requests and * a response interceptor that automatically expands compressed response * entities by wrapping them with a uncompressing decorator class. The use of - * protocol interceptors makes content compression completely transparent to + * protocol interceptors makes content compression completely transparent to * the consumer of the {@link org.apache.http.client.HttpClient HttpClient} * interface. */ @@ -62,65 +62,67 @@ 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() { - - 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; + }); + + 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; + } } } } - } - - }); - - 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); + + }); + + 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("Uncompressed size: "+content.length()); - } + 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()); + } - // 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } static class GzipDecompressingEntity extends HttpEntityWrapper { @@ -128,7 +130,7 @@ public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } - + @Override public InputStream getContent() throws IOException, IllegalStateException { @@ -145,7 +147,7 @@ return -1; } - } - + } + } --- httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java 2010-11-30 11:24:16.000000000 +0000 @@ -46,74 +46,76 @@ /** * A simple example that uses HttpClient to execute an HTTP request against - * a target site that requires user authentication. + * a target site that requires user authentication. */ public class ClientInteractiveAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + // Create local execution context + HttpContext localContext = new BasicHttpContext(); + + 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); - // Create local execution context - HttpContext localContext = new BasicHttpContext(); - - 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); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - - // Consume response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - - 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)); - - 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; + System.out.println(response.getStatusLine()); + + // Consume response content + HttpEntity entity = response.getEntity(); + if (entity != null) { + entity.consumeContent(); + } + + 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)); + + 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; + } 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } } --- httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java 2010-11-30 11:25:56.000000000 +0000 @@ -23,7 +23,7 @@ * . * */ - + package org.apache.http.examples.client; import org.apache.http.HttpEntity; @@ -41,13 +41,13 @@ import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; /** * An example that performs GETs from multiple threads. - * + * */ public class ClientMultiThreadedExecution { @@ -56,79 +56,81 @@ HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - - // Create and initialize scheme registry + + // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - + // Create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); - HttpClient httpClient = new DefaultHttpClient(cm, params); - - // create an array of URIs to perform GETs on - String[] urisToGet = { - "http://hc.apache.org/", - "http://hc.apache.org/httpcomponents-core/", - "http://hc.apache.org/httpcomponents-client/", - "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); - } - - // 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(); - } + HttpClient httpclient = new DefaultHttpClient(cm, params); + try { + // create an array of URIs to perform GETs on + String[] urisToGet = { + "http://hc.apache.org/", + "http://hc.apache.org/httpcomponents-core/", + "http://hc.apache.org/httpcomponents-client/", + "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); + } + + // start the threads + for (int j = 0; j < threads.length; j++) { + threads[j].start(); + } - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources - httpClient.getConnectionManager().shutdown(); + // 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } - + /** * A thread that performs a GET. */ static class GetThread extends Thread { - + private final HttpClient httpClient; private final HttpContext context; private final HttpGet httpget; private final int id; - + public GetThread(HttpClient httpClient, HttpGet httpget, int id) { this.httpClient = httpClient; this.context = new BasicHttpContext(); this.httpget = httpget; this.id = id; } - + /** * Executes the GetMethod and prints some status information. */ @Override public void run() { - + System.out.println(id + " - about to get something from " + httpget.getURI()); try { - + // execute the method HttpResponse response = httpClient.execute(httpget, context); - + System.out.println(id + " - get executed"); // get the response body as an array of bytes HttpEntity entity = response.getEntity(); @@ -136,13 +138,13 @@ byte[] bytes = EntityUtils.toByteArray(entity); System.out.println(id + " - " + bytes.length + " bytes read"); } - + } catch (Exception e) { httpget.abort(); System.out.println(id + " - error: " + e); } } - + } - + } --- httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java 2010-11-30 11:27:41.000000000 +0000 @@ -48,7 +48,7 @@ import org.apache.http.protocol.HttpContext; /** - * An example of HttpClient can be customized to authenticate + * An example of HttpClient can be customized to authenticate * preemptively using BASIC scheme. * * Generally, preemptive authentication can be considered less @@ -62,55 +62,57 @@ public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope("localhost", 80), + new UsernamePasswordCredentials("username", "password")); - httpclient.getCredentialsProvider().setCredentials( - new AuthScope("localhost", 80), - new UsernamePasswordCredentials("username", "password")); - - BasicHttpContext localcontext = new BasicHttpContext(); - - // Generate BASIC scheme object and stick it to the local - // execution context - BasicScheme basicAuth = new BasicScheme(); - localcontext.setAttribute("preemptive-auth", basicAuth); - - // Add as the first request interceptor - httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); - - HttpHost targetHost = new HttpHost("localhost", 80, "http"); - - HttpGet httpget = new HttpGet("/"); - - 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(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - entity.consumeContent(); + BasicHttpContext localcontext = new BasicHttpContext(); + + // Generate BASIC scheme object and stick it to the local + // execution context + BasicScheme basicAuth = new BasicScheme(); + localcontext.setAttribute("preemptive-auth", basicAuth); + + // Add as the first request interceptor + httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); + + HttpHost targetHost = new HttpHost("localhost", 80, "http"); + + HttpGet httpget = new HttpGet("/"); + + 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(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + entity.consumeContent(); + } } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } 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(); } - + static class PreemptiveAuth implements HttpRequestInterceptor { public void process( - final HttpRequest request, + final HttpRequest request, final HttpContext context) throws HttpException, IOException { - + AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); - + // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute( @@ -122,7 +124,7 @@ if (authScheme != null) { Credentials creds = credsProvider.getCredentials( new AuthScope( - targetHost.getHostName(), + targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); @@ -131,8 +133,8 @@ authState.setCredentials(creds); } } - + } - + } } --- httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java 2010-11-30 11:27:05.000000000 +0000 @@ -49,7 +49,7 @@ import org.apache.http.protocol.HttpContext; /** - * An example of HttpClient can be customized to authenticate + * An example of HttpClient can be customized to authenticate * preemptively using DIGEST scheme. * * Generally, preemptive authentication can be considered less @@ -63,60 +63,62 @@ public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); - - httpclient.getCredentialsProvider().setCredentials( - new AuthScope("localhost", 80), - new UsernamePasswordCredentials("username", "password")); - - BasicHttpContext localcontext = new BasicHttpContext(); - // Generate DIGEST scheme object, initialize it and stick it to - // the local execution context - 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"); - localcontext.setAttribute("preemptive-auth", digestAuth); - - // Add as the first request interceptor - httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); - // Add as the last response interceptor - httpclient.addResponseInterceptor(new PersistentDigest()); - - HttpHost targetHost = new HttpHost("localhost", 80, "http"); - - HttpGet httpget = new HttpGet("/"); - - 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(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - entity.consumeContent(); + try { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope("localhost", 80), + new UsernamePasswordCredentials("username", "password")); + + BasicHttpContext localcontext = new BasicHttpContext(); + // Generate DIGEST scheme object, initialize it and stick it to + // the local execution context + 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"); + localcontext.setAttribute("preemptive-auth", digestAuth); + + // Add as the first request interceptor + httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); + // Add as the last response interceptor + httpclient.addResponseInterceptor(new PersistentDigest()); + + HttpHost targetHost = new HttpHost("localhost", 80, "http"); + + HttpGet httpget = new HttpGet("/"); + + 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(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + entity.consumeContent(); + } } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } 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(); } - + static class PreemptiveAuth implements HttpRequestInterceptor { public void process( - final HttpRequest request, + final HttpRequest request, final HttpContext context) throws HttpException, IOException { - + AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); - + // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute( @@ -128,7 +130,7 @@ if (authScheme != null) { Credentials creds = credsProvider.getCredentials( new AuthScope( - targetHost.getHostName(), + targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); @@ -137,15 +139,15 @@ authState.setCredentials(creds); } } - + } - + } static class PersistentDigest implements HttpResponseInterceptor { public void process( - final HttpResponse response, + final HttpResponse response, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); @@ -159,7 +161,7 @@ } } } - + } - + } --- httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java 2010-11-30 11:26:29.000000000 +0000 @@ -35,45 +35,47 @@ import org.apache.http.impl.client.DefaultHttpClient; /** - * A simple example that uses HttpClient to execute an HTTP request - * over a secure connection tunneled through an authenticating proxy. + * A simple example that uses HttpClient to execute an HTTP request + * over a secure connection tunneled through an authenticating proxy. */ public class ClientProxyAuthentication { public static void main(String[] args) throws Exception { - - DefaultHttpClient httpclient = new DefaultHttpClient(); - 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); - - httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); - - HttpGet httpget = new HttpGet("/"); - - 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(); - - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); - if (entity != null) { - System.out.println("Response content length: " + entity.getContentLength()); - } - if (entity != null) { - entity.consumeContent(); + DefaultHttpClient httpclient = new DefaultHttpClient(); + try { + 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); + + httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); + + HttpGet httpget = new HttpGet("/"); + + 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(); + + System.out.println("----------------------------------------"); + System.out.println(response.getStatusLine()); + if (entity != null) { + System.out.println("Response content length: " + entity.getContentLength()); + } + if (entity != null) { + entity.consumeContent(); + } + + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + try { httpclient.getConnectionManager().shutdown(); } 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(); } } --- httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java 2010-11-30 10:54:54.000000000 +0000 @@ -42,22 +42,24 @@ public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); + try { + HttpGet httpget = new HttpGet("http://www.google.com/"); + + System.out.println("executing request " + httpget.getURI()); + + // Create a response handler + ResponseHandler responseHandler = new BasicResponseHandler(); + String responseBody = httpclient.execute(httpget, responseHandler); + System.out.println(responseBody); + + System.out.println("----------------------------------------"); - HttpGet httpget = new HttpGet("http://www.google.com/"); - - System.out.println("executing request " + httpget.getURI()); - - // Create a response handler - ResponseHandler responseHandler = new BasicResponseHandler(); - String responseBody = httpclient.execute(httpget, responseHandler); - 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 + try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} + } } } --- httpclient/src/examples/org/apache/http/examples/conn/OperatorConnectDirect.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/conn/OperatorConnectDirect.java 2010-11-30 11:35:58.000000000 +0000 @@ -43,8 +43,8 @@ import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; /** @@ -80,7 +80,7 @@ HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1); req.addHeader("Host", target.getHostName()); - + HttpContext ctx = new BasicHttpContext(); OperatedClientConnection conn = scop.createConnection(); @@ -104,7 +104,7 @@ System.out.println("----------------------------------------"); } finally { System.out.println("closing connection"); - conn.close(); + try { conn.close(); } catch (Exception ignore) {} } } --- httpclient/src/examples/org/apache/http/examples/conn/OperatorConnectProxy.java 2010-09-15 20:13:22.000000000 +0000 +++ httpclient/src/examples/org/apache/http/examples/conn/OperatorConnectProxy.java 2010-11-30 11:39:11.000000000 +0000 @@ -43,8 +43,8 @@ import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; /** * How to open a secure connection through a proxy using @@ -67,9 +67,9 @@ // Register the "http" and "https" protocol schemes, they are // required by the default operator to look up socket factories. SchemeRegistry supportedSchemes = new SchemeRegistry(); - supportedSchemes.register(new Scheme("http", + supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - supportedSchemes.register(new Scheme("https", + supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Prepare parameters. @@ -86,7 +86,7 @@ // In a real application, request interceptors should be used // to add the required headers. req.addHeader("Host", target.getHostName()); - + HttpContext ctx = new BasicHttpContext(); OperatedClientConnection conn = scop.createConnection(); @@ -97,7 +97,7 @@ // Creates a request to tunnel a connection. // For details see RFC 2817, section 5.2 String authority = target.getHostName() + ":" + target.getPort(); - HttpRequest connect = new BasicHttpRequest("CONNECT", authority, + HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1); // In a real application, request interceptors should be used // to add the required headers. @@ -147,7 +147,7 @@ } finally { System.out.println("closing connection"); - conn.close(); + try { conn.close(); } catch (Exception ignore) {} } }