Return-Path: X-Original-To: apmail-hc-commits-archive@www.apache.org Delivered-To: apmail-hc-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id AAB8310CB1 for ; Wed, 14 Aug 2013 18:42:28 +0000 (UTC) Received: (qmail 25348 invoked by uid 500); 14 Aug 2013 18:42:28 -0000 Delivered-To: apmail-hc-commits-archive@hc.apache.org Received: (qmail 25273 invoked by uid 500); 14 Aug 2013 18:42:24 -0000 Mailing-List: contact commits-help@hc.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: "HttpComponents Project" Delivered-To: mailing list commits@hc.apache.org Received: (qmail 25263 invoked by uid 99); 14 Aug 2013 18:42:22 -0000 Received: from athena.apache.org (HELO athena.apache.org) (140.211.11.136) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 14 Aug 2013 18:42:22 +0000 X-ASF-Spam-Status: No, hits=-2000.0 required=5.0 tests=ALL_TRUSTED,T_FRT_STOCK2 X-Spam-Check-By: apache.org Received: from [140.211.11.4] (HELO eris.apache.org) (140.211.11.4) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 14 Aug 2013 18:42:19 +0000 Received: from eris.apache.org (localhost [127.0.0.1]) by eris.apache.org (Postfix) with ESMTP id 88CB22388860 for ; Wed, 14 Aug 2013 18:41:59 +0000 (UTC) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r1514003 - in /httpcomponents/httpclient/trunk/src/docbkx: advanced.xml authentication.xml caching.xml connmgmt.xml fluent.xml fundamentals.xml httpagent.xml index.xml statemgmt.xml Date: Wed, 14 Aug 2013 18:41:59 -0000 To: commits@hc.apache.org From: olegk@apache.org X-Mailer: svnmailer-1.0.9 Message-Id: <20130814184159.88CB22388860@eris.apache.org> X-Virus-Checked: Checked by ClamAV on apache.org Author: olegk Date: Wed Aug 14 18:41:58 2013 New Revision: 1514003 URL: http://svn.apache.org/r1514003 Log: Updated HttpClient tutorial to 4.3 APIs (fundamentals, auth, caching and fluent facade chapters) Removed: httpcomponents/httpclient/trunk/src/docbkx/httpagent.xml Modified: httpcomponents/httpclient/trunk/src/docbkx/advanced.xml httpcomponents/httpclient/trunk/src/docbkx/authentication.xml httpcomponents/httpclient/trunk/src/docbkx/caching.xml httpcomponents/httpclient/trunk/src/docbkx/connmgmt.xml httpcomponents/httpclient/trunk/src/docbkx/fluent.xml httpcomponents/httpclient/trunk/src/docbkx/fundamentals.xml httpcomponents/httpclient/trunk/src/docbkx/index.xml httpcomponents/httpclient/trunk/src/docbkx/statemgmt.xml Modified: httpcomponents/httpclient/trunk/src/docbkx/advanced.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/advanced.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/advanced.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/advanced.xml Wed Aug 14 18:41:58 2013 @@ -42,80 +42,38 @@ class MyLineParser extends BasicLinePars @Override public Header parseHeader( - final CharArrayBuffer buffer) throws ParseException { + CharArrayBuffer buffer) throws ParseException { try { return super.parseHeader(buffer); } catch (ParseException ex) { // Suppress ParseException exception - return new BasicHeader("invalid", buffer.toString()); + return new BasicHeader(buffer.toString(), null); } } - -} -]]> - - - Provide a custom OperatedClientConnection - implementation. Replace default request / response parsers, request / response - formatters with custom ones as required. Implement different message writing / - reading code if necessary. - - Provide a custom ClientConnectionOperator - interface implementation in order to create connections of new class. Implement - different socket initialization code if necessary. + Provide a custom HttpConnectionFactory + implementation. Replace default request writer and / or response parser + with custom ones as required. connFactory = + new ManagedHttpClientConnectionFactory( + new DefaultHttpRequestWriterFactory(), + new DefaultHttpResponseParserFactory( + new MyLineParser(), new DefaultHttpResponseFactory())); ]]> - Provide a custom ClientConnectionManager - interface implementation in order to create connection operator of new - class. + Configure HttpClient to use the custom connection factory. @@ -145,73 +103,62 @@ class MyClientConnManager extends Single connection based authentication schemes such as NTLM or that of the SSL session with client authentication turned on. If both are unavailable, null token will be returned. + Users can provide a custom implementation if the default one does not satisfy their needs:
- User token and execution context - In the course of HTTP request execution HttpClient adds the following user - identity related objects to the execution context: - - - - <constant>ClientContext.USER_TOKEN</constant>='http.user-token': - Object instance representing the actual user identity, usually - expected to be an instance of Principle - interface - - - - One can find out whether or not the connection used to execute the request was - stateful by examining the content of the local HTTP context after the request has - been executed. + Persistent stateful connections + Please note that a persistent connection that carries a state object can be reused + only if the same state object is bound to the execution context when requests + are executed. So, it is really important to ensure the either same context is + reused for execution of subsequent HTTP requests by the same user or the user + token is bound to the context prior to request execution. -
- Persistent stateful connections - Please note that a persistent connection that carries a state object can be reused - only if the same state object is bound to the execution context when requests - are executed. So, it is really important to ensure the either same context is - reused for execution of subsequent HTTP requests by the same user or the user - token is bound to the context prior to request execution. - -
- - Modified: httpcomponents/httpclient/trunk/src/docbkx/authentication.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/authentication.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/authentication.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/authentication.xml Wed Aug 14 18:41:58 2013 @@ -133,100 +133,6 @@ pwd
- HTTP authentication parameters - These are parameters that be used to customize the HTTP authentication process and - behaviour of individual authentication schemes: - - - - <constant>ClientPNames.HANDLE_AUTHENTICATION</constant>='http.protocol.handle-authentication': - defines whether authentication should be handled automatically. This - parameter expects a value of type java.lang.Boolean. - If this parameter is not set, HttpClient will handle authentication - automatically. - - - - - <constant>AuthPNames.CREDENTIAL_CHARSET</constant>='http.auth.credential-charset': - defines the charset to be used when encoding user credentials. This - parameter expects a value of type java.lang.String. If - this parameter is not set, US-ASCII will be used. - - - - - <constant>AuthPNames.TARGET_AUTH_PREF</constant>='http.auth.target-scheme-pref': - Defines the order of preference for supported - AuthSchemes when authenticating with the - target host. This parameter expects a value of type - java.util.Collection. The collection is expected - to contain java.lang.String instances representing - an id of an authentication scheme. - - - - - <constant>AuthPNames.PROXY_AUTH_PREF</constant>='http.auth.proxy-scheme-pref': - Defines the order of preference for supported - AuthSchemes when authenticating with the - proxy host. This parameter expects a value of type - java.util.Collection. The collection is expected - to contain java.lang.String instances representing - an id of an authentication scheme. - - - - For example, one can force HttpClient to use a different order of preference for - authentication schemes - authpref = new ArrayList(); -authpref.add(AuthPolicy.BASIC); -authpref.add(AuthPolicy.DIGEST); -httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); -]]> -
-
- Authentication scheme registry - HttpClient maintains a registry of available authentication schemes using - the AuthSchemeRegistry class. The following schemes are - registered per default: - - - - AuthPolicy.BASIC: - Basic authentication - - - - - AuthPolicy.DIGEST: - Digest authentication - - - - - AuthPolicy.NTLM: - NTLMv1, NTLMv2, and NTLM2 Session authentication - - - - - AuthPolicy.SPNEGO: - SPNEGO authentication - - - - - AuthPolicy.KERBEROS: - Kerberos authentication - - - -
-
Credentials provider Credentials providers are intended to maintain a set of user credentials and to be able to produce user credentials for a particular authentication scope. Authentication @@ -289,23 +195,20 @@ null - <constant>ClientContext.AUTHSCHEME_REGISTRY</constant>='http.authscheme-registry': - AuthSchemeRegistry instance representing the actual + Lookup instance representing the actual authentication scheme registry. The value of this attribute set in the local context takes precedence over the default one. - <constant>ClientContext.CREDS_PROVIDER</constant>='http.auth.credentials-provider': - CookieSpec instance representing the actual - credentials provider. The value of this attribute set in the local context - takes precedence over the default one. + CredentialsProvider instance representing + the actual credentials provider. The value of this attribute set in the + local context takes precedence over the default one. - <constant>ClientContext.TARGET_AUTH_STATE</constant>='http.auth.target-scope': AuthState instance representing the actual target authentication state. The value of this attribute set in the local context takes precedence over the default one. @@ -313,7 +216,6 @@ null - <constant>ClientContext.PROXY_AUTH_STATE</constant>='http.auth.proxy-scope': AuthState instance representing the actual proxy authentication state. The value of this attribute set in the local context takes precedence over the default one. @@ -321,7 +223,6 @@ null - <constant>ClientContext.AUTH_CACHE</constant>='http.auth.auth-cache': AuthCache instance representing the actual authentication data cache. The value of this attribute set in the local context takes precedence over the default one. @@ -332,18 +233,25 @@ null the HTTP authentication context prior to request execution, or to examine its state after the request has been executed: + +CredentialsProvider credsProvider = <...> +Lookup authRegistry = <...> +AuthCache authCache = <...> + +HttpClientContext context = HttpClientContext.create(); +context.setCredentialsProvider(credsProvider); +context.setAuthSchemeRegistry(authRegistry); +context.setAuthCache(authCache); +HttpGet httpget = new HttpGet("http://somehost/"); +CloseableHttpResponse response1 = httpclient.execute(httpget, context); +<...> -AuthState proxyAuthState = (AuthState) localContext.getAttribute( - ClientContext.PROXY_AUTH_STATE); +AuthState proxyAuthState = context.getProxyAuthState(); System.out.println("Proxy auth state: " + proxyAuthState.getState()); System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme()); System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials()); -AuthState targetAuthState = (AuthState) localContext.getAttribute( - ClientContext.TARGET_AUTH_STATE); +AuthState targetAuthState = context.getTargetAuthState(); System.out.println("Target auth state: " + targetAuthState.getState()); System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme()); System.out.println("Target auth credentials: " + targetAuthState.getCredentials()); @@ -368,12 +276,12 @@ System.out.println("Target auth credenti Nonethess one can configure HttpClient to authenticate preemptively by prepopulating the authentication data cache. -httpclient.getCredentialsProvider().setCredentials( - new AuthScope(targetHost.getHostName(), targetHost.getPort()), +HttpHost targetHost = new HttpHost("localhost", 80, "http"); +CredentialsProvider credsProvider = new BasicCredentialsProvider(); +credsProvider.setCredentials( + new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("username", "password")); // Create AuthCache instance @@ -383,14 +291,19 @@ BasicScheme basicAuth = new BasicScheme( authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context -BasicHttpContext localcontext = new BasicHttpContext(); -localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); +HttpClientContext context = HttpClientContext.create(); +context.setCredentialsProvider(credsProvider); HttpGet httpget = new HttpGet("/"); for (int i = 0; i < 3; i++) { - HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); - HttpEntity entity = response.getEntity(); - EntityUtils.consume(entity); + CloseableHttpResponse response = httpclient.execute( + targetHost, httpget, context); + try { + HttpEntity entity = response.getEntity(); + + } finally { + response.close(); + } } ]]>
@@ -428,28 +341,36 @@ for (int i = 0; i < 3; i++) { connection to execute more expensive methods, especially those enclose a request entity, such as POST or PUT. -NTCredentials creds = new NTCredentials("user", "pwd", "myworkstation", "microsoft.com"); -httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); +CredentialsProvider credsProvider = new BasicCredentialsProvider(); +credsProvider.setCredentials(AuthScope.ANY, + new NTCredentials("user", "pwd", "myworkstation", "microsoft.com")); HttpHost target = new HttpHost("www.microsoft.com", 80, "http"); // Make sure the same context is used to execute logically related requests -HttpContext localContext = new BasicHttpContext(); +HttpClientContext context = HttpClientContext.create(); +context.setCredentialsProvider(credsProvider); // Execute a cheap method first. This will trigger NTLM authentication HttpGet httpget = new HttpGet("/ntlm-protected/info"); -HttpResponse response1 = httpclient.execute(target, httpget, localContext); -HttpEntity entity1 = response1.getEntity(); -EntityUtils.consume(entity1); +CloseableHttpResponse response1 = httpclient.execute(target, httpget, context); +try { + HttpEntity entity1 = response1.getEntity(); +} finally { + response1.close(); +} // Execute an expensive method next reusing the same context (and connection) HttpPost httppost = new HttpPost("/ntlm-protected/form"); httppost.setEntity(new StringEntity("lots and lots of data")); -HttpResponse response2 = httpclient.execute(target, httppost, localContext); -HttpEntity entity2 = response2.getEntity(); -EntityUtils.consume(entity2); +CloseableHttpResponse response2 = httpclient.execute(target, httppost, context); +try { + HttpEntity entity2 = response2.getEntity(); +} finally { + response2.close(); +} ]]> Modified: httpcomponents/httpclient/trunk/src/docbkx/caching.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/caching.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/caching.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/caching.xml Wed Aug 14 18:41:58 2013 @@ -29,29 +29,30 @@ HttpClient Cache provides an HTTP/1.1-compliant caching layer to be used with HttpClient--the Java equivalent of a browser cache. The - implementation follows the Decorator design pattern, where the - CachingHttpClient class is a drop-in replacement for - a DefaultHttpClient; requests that can be satisfied entirely from the cache - will not result in actual origin requests. Stale cache entries are - automatically validated with the origin where possible, using conditional GETs - and the If-Modified-Since and/or If-None-Match request headers. + implementation follows the Chain of Responsibility design pattern, where the + caching HttpClient implementation can serve a drop-in replacement for + the default non-caching HttpClient implementation; requests that can be + satisfied entirely from the cache will not result in actual origin requests. + Stale cache entries are automatically validated with the origin where possible, + using conditional GETs and the If-Modified-Since and/or If-None-Match request + headers. HTTP/1.1 caching in general is designed to be semantically transparent; that is, a cache should not change the meaning of the request-response exchange between client and server. As such, it should - be safe to drop a CachingHttpClient into an existing compliant client-server + be safe to drop a caching HttpClient into an existing compliant client-server relationship. Although the caching module is part of the client from an HTTP protocol point of view, the implementation aims to be compatible with the requirements placed on a transparent caching proxy. - Finally, CachingHttpClient includes support the Cache-Control + Finally, caching HttpClient includes support the Cache-Control extensions specified by RFC 5861 (stale-if-error and stale-while-revalidate). - When CachingHttpClient executes a request, it goes through the + When caching HttpClient executes a request, it goes through the following flow: @@ -90,7 +91,7 @@ - When CachingHttpClient receives a response, it goes through the + When caching HttpClient receives a response, it goes through the following flow: @@ -114,10 +115,10 @@ - It is important to note that CachingHttpClient is not, itself, an - implementation of HttpClient, but that it decorates an instance of an - HttpClient implementation. If you do not provide an implementation, it - will use DefaultHttpClient internally by default. + It is important to note that caching HttpClient is not, itself, + a different implementation of HttpClient, but that it works by inserting + itself as an additonal processing component to the request execution + pipeline.
@@ -135,41 +136,50 @@
Example Usage - This is a simple example of how to set up a basic CachingHttpClient. + This is a simple example of how to set up a basic caching HttpClient. As configured, it will store a maximum of 1000 cached objects, each of which may have a maximum body size of 8192 bytes. The numbers selected here are for example only and not intended to be prescriptive or considered as recommendations. @@ -178,11 +188,11 @@ case VALIDATED:
Configuration - As the CachingHttpClient is a decorator, much of the configuration you may - want to do can be done on the HttpClient used as the "backend" by the HttpClient - (this includes setting options like timeouts and connection pool sizes). For - caching-specific configuration, you can provide a CacheConfig instance to - customize behavior across the following areas: + The caching HttpClient inherits all configuration options and parameters + of the default non-caching implementation (this includes setting options like + timeouts and connection pool sizes). For caching-specific configuration, you can + provide a CacheConfig instance to customize behavior + across the following areas: Cache size. If the backend storage supports these limits, you can specify the maximum number of cache entries as well as the maximum cacheable @@ -217,7 +227,7 @@ case VALIDATED:
Storage Backends - The default implementation of CachingHttpClient stores cache entries and + The default implementation of caching HttpClient stores cache entries and cached response bodies in memory in the JVM of your application. While this offers high performance, it may not be appropriate for your application due to the limitation on size or because the cache entries are ephemeral and don't @@ -227,18 +237,17 @@ case VALIDATED: If none of those options are suitable for your application, it is possible to provide your own storage backend by implementing the HttpCacheStorage - interface and then supplying that to CachingHttpClient at construction time. In + interface and then supplying that to caching HttpClient at construction time. In this case, the cache entries will be stored using your scheme but you will get to reuse all of the logic surrounding HTTP/1.1 compliance and cache handling. Generally speaking, it should be possible to create an HttpCacheStorage implementation out of anything that supports a key/value store (similar to the Java Map interface) with the ability to apply atomic updates. - Finally, because the CachingHttpClient is a decorator for HttpClient, - it's entirely possible to set up a multi-tier caching hierarchy; for example, - wrapping an in-memory CachingHttpClient around one that stores cache entries on - disk or remotely in memcached, following a pattern similar to virtual memory, - L1/L2 processor caches, etc. + Finally, with some extra efforts it's entirely possible to set up + a multi-tier caching hierarchy; for example, wrapping an in-memory caching + HttpClient around one that stores cache entries on disk or remotely in memcached, + following a pattern similar to virtual memory, L1/L2 processor caches, etc.
Modified: httpcomponents/httpclient/trunk/src/docbkx/connmgmt.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/connmgmt.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/connmgmt.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/connmgmt.xml Wed Aug 14 18:41:58 2013 @@ -415,12 +415,12 @@ sf.connectSocket(timeout, socket, target LayeredConnectionSocketFactory sslsf = <...> -Registry reg = RegistryBuilder.create() +Registry r = RegistryBuilder.create() .register("http", plainsf) .register("https", sslsf) .build(); -HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg); +HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r); HttpClients.custom() .setConnectionManager(cm) .build(); Modified: httpcomponents/httpclient/trunk/src/docbkx/fluent.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/fluent.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/fluent.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/fluent.xml Wed Aug 14 18:41:58 2013 @@ -108,7 +108,8 @@ Document result = Request.Get("http://so DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.equals(ContentType.APPLICATION_XML)) { - throw new ClientProtocolException("Unexpected content type:" + contentType); + throw new ClientProtocolException("Unexpected content type:" + + contentType); } String charset = contentType.getCharset(); if (charset == null) { @@ -126,44 +127,5 @@ Document result = Request.Get("http://so ]]>
-
- Asynchronous execution - The fluent facade API can be used to execute multiple requests asynchronously using - background threads. - - > queue = new LinkedList>(); -for (final Request request: requests) { - Future future = async.execute(request, new FutureCallback() { - - public void failed(final Exception ex) { - System.out.println(ex.getMessage() + ": " + request); - } - - public void completed(final Content content) { - System.out.println("Request completed: " + request); - } - - public void cancelled() { - } - - }); - queue.add(future); -} - -// Process the queue -]]> - -
Modified: httpcomponents/httpclient/trunk/src/docbkx/fundamentals.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/fundamentals.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/fundamentals.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/fundamentals.xml Wed Aug 14 18:41:58 2013 @@ -38,7 +38,7 @@ CloseableHttpClient httpclient = HttpCli HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { - + <...> } finally { response.close(); } @@ -283,7 +283,8 @@ important message In order to ensure proper release of system resources one must close either the content stream associated with the entity or the response itself +CloseableHttpClient httpclient = HttpClients.createDefault(); +HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); @@ -318,7 +319,8 @@ try { remaining content and making the connection reusable is too high, in which case one can terminate the content stream by closing the response. +CloseableHttpClient httpclient = HttpClients.createDefault(); +HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); @@ -348,7 +350,8 @@ try { strongly discouraged unless the response entities originate from a trusted HTTP server and are known to be of limited length. +CloseableHttpClient httpclient = HttpClients.createDefault(); +HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); @@ -452,8 +455,8 @@ httppost.setEntity(entity); take care of ensuring release of the connection back to the connection manager regardless whether the request execution succeeds or causes an exception. -HttpRequest request = <...> +CloseableHttpClient httpclient = HttpClients.createDefault(); +HttpGet httpget = new HttpGet("http://localhost/json"); ResponseHandler rh = new ResponseHandler() { @@ -477,7 +480,64 @@ ResponseHandler rh = new R return gson.fromJson(reader, MyJsonObject.class); } }; -MyJsonObject myjson = client.execute(request, rh); +MyJsonObject myjson = client.execute(httpget, rh); +]]> +
+ +
+ HttpClient interface + HttpClient interface represents the most essential + contract for HTTP request execution. It imposes no restrictions or particular details on + the request execution process and leaves the specifics of connection management, state + management, authentication and redirect handling up to individual implementations. This + should make it easier to decorate the interface with additional functionality such as + response content caching. + Generally HttpClient implementations act as a facade + to a number of special purpose handler or strategy interface implementations + responsible for handling of a particular aspect of the HTTP protocol such as redirect + or authentication handling or making decision about connection persistence and keep + alive duration. This enables the users to selectively replace default implementation + of those aspects with custom, application specific ones. + +
+ HttpClient thread safety + HttpClient implementations are expected to be + thread safe. It is recommended that the same instance of this class is reused for + multiple request executions. +
+
+ HttpClient resource deallocation + When an instance CloseableHttpClient is no longer needed + and is about to go out of scope the connection manager associated with it must + be shut down by calling the CloseableHttpClient#close() + method. + +} finally { + httpclient.close(); +} ]]>
@@ -497,6 +557,64 @@ MyJsonObject myjson = client.execute(req HttpContext can contain arbitrary objects and therefore may be unsafe to share between multiple threads. It is recommended that each thread of execution maintains its own context. + In the course of HTTP request execution HttpClient adds the following attributes to + the execution context: + + + + HttpConnection instance representing the + actual connection to the target server. + + + + + HttpHost instance representing the connection + target. + + + + + HttpRoute instance representing the complete + connection route + + + + + HttpRequest instance representing the + actual HTTP request. The final HttpRequest object in the execution context + always represents the state of the message exactly + as it was sent to the target server. Per default HTTP/1.0 and HTTP/1.1 + use relative request URIs. However if the request is sent via a proxy + in a non-tunneling mode then the URI will be absolute. + + + + + HttpResponse instance representing the + actual HTTP response. + + + + + java.lang.Boolean object representing the flag + indicating whether the actual request has been fully transmitted to the + connection target. + + + + + RequestConfig object representing the actual + request configuation. + + + + + URICollection object representing a collection + of all redirect locations received in the process of request + execution. + + + One can use HttpClientContext adaptor class to simplify interractions with the context state. Multiple request sequences that represent a logically related session should be executed with the same HttpContext instance to ensure @@ -514,8 +633,7 @@ HttpResponse response = clientContext.ge kept in the execution context and get propagatd to the consecutive requests sharing the same context. - +CloseableHttpClient httpclient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(1000) .setConnectTimeout(1000) @@ -720,4 +838,44 @@ for (int i = 0; i < 10; i++) { } ]]> +
+ Redirect handling + HttpClient handles all types of redirects automatically, except those explicitly + prohibited by the HTTP specification as requiring user intervention. See + Other (status code 303) redirects on POST and + PUT requests are converted to GET requests as + required by the HTTP specification. One can use a custom redirect strategy to relaxe + restrictions on automatic redirection of POST methods imposed by the HTTP + specification. + + HttpClient often has to rewrite the request message in the process of its execution. + Per default HTTP/1.0 and HTTP/1.1 generally use relative request URIs. Likewise, + original request may get redirected from location to another multiple times. The final + interpreted absolute HTTP location can be built using the original request and + the context. The utility method URIUtils#resolve can be used + to build the interpreted absolute URI used to generate the final request. This method + includes the last fragment identifier from the redirect requests or the original + request. + +
Modified: httpcomponents/httpclient/trunk/src/docbkx/index.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/index.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/index.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/index.xml Wed Aug 14 18:41:58 2013 @@ -32,10 +32,14 @@ Oleg Kalnichevski + + Jonathan + Moore + - + Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information @@ -43,18 +47,18 @@ to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - - + + - - + + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - + @@ -65,7 +69,6 @@ - Modified: httpcomponents/httpclient/trunk/src/docbkx/statemgmt.xml URL: http://svn.apache.org/viewvc/httpcomponents/httpclient/trunk/src/docbkx/statemgmt.xml?rev=1514003&r1=1514002&r2=1514003&view=diff ============================================================================== --- httpcomponents/httpclient/trunk/src/docbkx/statemgmt.xml (original) +++ httpcomponents/httpclient/trunk/src/docbkx/statemgmt.xml Wed Aug 14 18:41:58 2013 @@ -205,9 +205,11 @@ CookieSpecProvider easySpecProvider = ne } }; -Registry cookieSpecReg = RegistryBuilder.create() - .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) - .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()) +Registry r = RegistryBuilder.create() + .register(CookieSpecs.BEST_MATCH, + new BestMatchSpecFactory()) + .register(CookieSpecs.BROWSER_COMPATIBILITY, + new BrowserCompatSpecFactory()) .register("easy", easySpecProvider) .build(); @@ -216,7 +218,7 @@ RequestConfig requestConfig = RequestCon .build(); CloseableHttpClient httpclient = HttpClients.custom() - .setDefaultCookieSpecRegistry(cookieSpecReg) + .setDefaultCookieSpecRegistry(r) .setDefaultRequestConfig(requestConfig) .build(); ]]> @@ -253,7 +255,7 @@ CloseableHttpClient httpclient = HttpCli - CookieSpecRegistry instance representing the actual + Lookup instance representing the actual cookie specification registry. The value of this attribute set in the local context takes precedence over the default one. @@ -287,13 +289,13 @@ CloseableHttpClient httpclient = HttpCli -Registry cookieSpecReg = <...> +Lookup cookieSpecReg = <...> CookieStore cookieStore = <...> HttpClientContext context = HttpClientContext.create(); context.setCookieSpecRegistry(cookieSpecReg); context.setCookieStore(cookieStore); -HttpGet httpget = new HttpGet("http://localhost/1"); +HttpGet httpget = new HttpGet("http://somehost/"); CloseableHttpResponse response1 = httpclient.execute(httpget, context); <...> // Cookie origin details