Httpclient Tutorial
Httpclient Tutorial
Oleg Kalnichevski
Preface ................................................................................................................................... iv 1. HttpClient scope ......................................................................................................... iv 2. What HttpClient is NOT ............................................................................................. iv 1. Fundamentals ....................................................................................................................... 1 1.1. Request execution ..................................................................................................... 1 1.1.1. HTTP request ................................................................................................. 1 1.1.2. HTTP response ............................................................................................... 2 1.1.3. Working with message headers ........................................................................ 2 1.1.4. HTTP entity ................................................................................................... 4 1.1.5. Ensuring release of low level resources ............................................................ 5 1.1.6. Consuming entity content ................................................................................ 5 1.1.7. Producing entity content .................................................................................. 6 1.1.8. Response handlers .......................................................................................... 7 1.2. HTTP execution context ............................................................................................ 8 1.3. Exception handling .................................................................................................... 9 1.3.1. HTTP transport safety ..................................................................................... 9 1.3.2. Idempotent methods ........................................................................................ 9 1.3.3. Automatic exception recovery ........................................................................ 10 1.3.4. Request retry handler .................................................................................... 10 1.4. Aborting requests .................................................................................................... 11 1.5. HTTP protocol interceptors ...................................................................................... 11 1.6. HTTP parameters .................................................................................................... 12 1.6.1. Parameter hierarchies .................................................................................... 12 1.6.2. HTTP parameters beans ................................................................................ 13 1.7. HTTP request execution parameters .......................................................................... 13 2. Connection management ..................................................................................................... 15 2.1. Connection parameters ............................................................................................. 15 2.2. Connection persistence ............................................................................................. 16 2.3. HTTP connection routing ......................................................................................... 16 2.3.1. Route computation ........................................................................................ 16 2.3.2. Secure HTTP connections ............................................................................. 17 2.4. HTTP route parameters ............................................................................................ 17 2.5. Socket factories ....................................................................................................... 17 2.5.1. Secure socket layering ................................................................................... 18 2.5.2. SSL/TLS customization ................................................................................. 18 2.5.3. Hostname verification ................................................................................... 18 2.6. Protocol schemes ..................................................................................................... 19 2.7. HttpClient proxy configuration ................................................................................. 19 2.8. HTTP connection managers ..................................................................................... 20 2.8.1. Connection operators ..................................................................................... 20 2.8.2. Managed connections and connection managers .............................................. 20 2.8.3. Simple connection manager ........................................................................... 22 2.8.4. Pooling connection manager .......................................................................... 22 2.8.5. Connection manager shutdown ...................................................................... 23 2.9. Connection management parameters ......................................................................... 23 2.10. Multithreaded request execution ............................................................................. 23 2.11. Connection eviction policy ..................................................................................... 24 2.12. Connection keep alive strategy ............................................................................... 25 3. HTTP state management ..................................................................................................... 27
ii
HttpClient Tutorial 3.1. HTTP cookies ......................................................................................................... 3.1.1. Cookie versions ............................................................................................ 3.2. Cookie specifications ............................................................................................... 3.3. HTTP cookie and state management parameters ........................................................ 3.4. Cookie specification registry .................................................................................... 3.5. Choosing cookie policy ............................................................................................ 3.6. Custom cookie policy .............................................................................................. 3.7. Cookie persistence ................................................................................................... 3.8. HTTP state management and execution context ......................................................... 3.9. Per user / thread state management ........................................................................... 4. HTTP authentication .......................................................................................................... 4.1. User credentials ....................................................................................................... 4.2. Authentication schemes ............................................................................................ 4.3. HTTP authentication parameters ............................................................................... 4.4. Authentication scheme registry ................................................................................. 4.5. Credentials provider ................................................................................................. 4.6. HTTP authentication and execution context ............................................................... 4.7. Preemptive authentication ........................................................................................ 4.8. NTLM Authentication .............................................................................................. 4.8.1. NTLM connection persistence ....................................................................... 5. HTTP client service ........................................................................................................... 5.1. HttpClient facade ..................................................................................................... 5.2. HttpClient parameters .............................................................................................. 5.3. Automcatic redirect handling .................................................................................... 5.4. HTTP client and execution context ........................................................................... 6. Advanced topics ................................................................................................................. 6.1. Custom client connections ........................................................................................ 6.2. Stateful HTTP connections ....................................................................................... 6.2.1. User token handler ........................................................................................ 6.2.2. User token and execution context .................................................................. 27 27 28 29 29 29 30 30 30 31 32 32 32 33 33 33 34 35 36 36 38 38 39 39 40 41 41 42 42 43
iii
Preface
The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support. Although the java.net package provides basic functionality for accessing resources via HTTP, it doesn't provide the full flexibility or functionality needed by many applications. HttpClient seeks to fill this void by providing an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations. Designed for extension while providing robust support for the base HTTP protocol, HttpClient may be of interest to anyone building HTTP-aware client applications such as web browsers, web service clients, or systems that leverage or extend the HTTP protocol for distributed communication.
1. HttpClient scope
Client-side HTTP transport library based on HttpCore [http://hc.apache.org/httpcomponents-core/ index.html] Based on classic (blocking) I/O Content agnostic
iv
Chapter 1. Fundamentals
1.1. Request execution
The most essential function of HttpClient is to execute HTTP methods. Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient. The user is expected to provide a request object to execute and HttpClient is expected to transmit the request to the target server return a corresponding response object, or throw an exception if execution was unsuccessful. Quite naturally, the main entry point of the HttpClient API is the HttpClient interface that defines the contract described above. Here is an example of request execution process in its simplest form:
HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://localhost/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); int l; byte[] tmp = new byte[2048]; while ((l = instream.read(tmp)) != -1) { } }
HttpClient provides a number of utility methods to simplify creation and modification of request URIs. URI can be assembled programmatically:
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", "q=httpclient&btnG=Google+Search&aq=f&oq=", null); HttpGet httpget = new HttpGet(uri); System.out.println(httpget.getURI());
stdout >
Fundamentals
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("q", "httpclient")); qparams.add(new BasicNameValuePair("btnG", "Google Search")); qparams.add(new BasicNameValuePair("aq", "f")); qparams.add(new BasicNameValuePair("oq", null)); URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet httpget = new HttpGet(uri); System.out.println(httpget.getURI());
stdout >
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); System.out.println(response.getProtocolVersion()); System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getStatusLine().getReasonPhrase()); System.out.println(response.getStatusLine().toString());
stdout >
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost"); response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\""); Header h1 = response.getFirstHeader("Set-Cookie"); System.out.println(h1); Header h2 = response.getLastHeader("Set-Cookie");
Fundamentals
System.out.println(h2); Header[] hs = response.getHeaders("Set-Cookie"); System.out.println(hs.length);
stdout >
The most efficient way to obtain all headers of a given type is by using the HeaderIterator interface.
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost"); response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\""); HeaderIterator it = response.headerIterator("Set-Cookie"); while (it.hasNext()) { System.out.println(it.next()); }
stdout >
It also provides convenience methods to parse HTTP messages into individual header elements.
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost"); response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\""); HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator("Set-Cookie")); while (it.hasNext()) { HeaderElement elem = it.nextElement(); System.out.println(elem.getName() + " = " + elem.getValue()); NameValuePair[] params = elem.getParameters(); for (int i = 0; i < params.length; i++) { System.out.println(" " + params[i]); } }
stdout >
Fundamentals
domain=localhost
This distinction is important for connection management when streaming out content from an HTTP response. For request entities that are created by an application and only sent using HttpClient, the difference between streamed and self-contained is of little importance. In that case, it is suggested to consider non-repeatable entities as streamed, and those that are repeatable as self-contained. 1.1.4.1. Repeatable entities An entity can be repeatable, meaning its content can be read more than once. This is only possible with self contained entities (like ByteArrayEntity or StringEntity) 1.1.4.2. Using HTTP entities Since an entity can represent both binary and character content, it has support for character encodings (to support the latter, ie. character content). The entity is created when executing a request with enclosed content or when the request was successful and the response body is used to send the result back to the client. To read the content from the entity, one can either retrieve the input stream via the HttpEntity#getContent() method, which returns an java.io.InputStream, or one can supply an output stream to the HttpEntity#writeTo(OutputStream) method, which will return once all content has been written to the given stream. When been received with an incoming message, the methods HttpEntity#getContentType() and HttpEntity#getContentLength() methods can be used for reading the common metadata such as Content-Type and Content-Length headers (if they are available). Since the Content-Type header can contain a character encoding for text mime-types like text/plain or text/html, the HttpEntity#getContentEncoding() method is used to read this information. If the headers aren't available, a length of -1 will be returned, and NULL for the content type. If the Content-Type header is available, a Header object will be returned. the entity has
Fundamentals When creating an entity for a outgoing message, this meta data has to be supplied by the creator of the entity.
StringEntity myEntity = new StringEntity("important message", "UTF-8"); System.out.println(myEntity.getContentType()); System.out.println(myEntity.getContentLength()); System.out.println(EntityUtils.getContentCharSet(myEntity)); System.out.println(EntityUtils.toString(myEntity)); System.out.println(EntityUtils.toByteArray(myEntity).length);
stdout >
HttpGet httpget = new HttpGet("http://localhost/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); int byteOne = instream.read(); int byteTwo = instream.read(); // Do not need the rest httpget.abort(); }
The connection will not be reused, but all level resources held by it will be correctly deallocated.
Fundamentals discouraged unless the response entities originate from a trusted HTTP server and are known to be of limited length.
HttpGet httpget = new HttpGet("http://localhost/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { System.out.println(EntityUtils.toString(entity)); } else { // Stream content out } }
In some situations it may be necessary to be able to read entity content more than once. In this case entity content must be buffered in some way, either in memory or on disk. The simplest way to accomplish that is by wrapping the original entity with the BufferedHttpEntity class. This will cause the content of the original entity to be read into a in-memory buffer. In all other ways the entity wrapper will be have the original one.
HttpGet httpget = new HttpGet("http://localhost/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { entity = new BufferedHttpEntity(entity); }
File file = new File("somefile.txt"); FileEntity entity = new FileEntity(file, "text/plain; charset=\"UTF-8\""); HttpPost httppost = new HttpPost("http://localhost/action.do"); httppost.setEntity(entity);
Please note InputStreamEntity is not repeatable, because it can only read from the underlying data stream once. Generally it is recommended to implement a custom HttpEntity class which is selfcontained instead of using generic InputStreamEntity. FileEntity can be a good starting point. 1.1.7.1. Dynamic content entities Often HTTP entities need to be generated dynamically based a particular execution context. HttpClient provides support for dynamic entities by using EntityTemplate entity class and ContentProducer interface. Content producers are objects which produce their content on demand, by writing it out to an output stream. They are expected to be able produce their content every time they are requested to do so. So entities created with EntityTemplate are generally self-contained and repeatable.
Fundamentals
ContentProducer cp = new ContentProducer() { public void writeTo(OutputStream outstream) throws IOException { Writer writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<response>"); writer.write(" <content>"); writer.write(" important stuff"); writer.write(" </content>"); writer.write("</response>"); writer.flush(); } }; HttpEntity entity = new EntityTemplate(cp); HttpPost httppost = new HttpPost("http://localhost/handler.do"); httppost.setEntity(entity);
1.1.7.2. HTML forms Many applications frequently need to simulate the process of submitting an HTML form, for instance, in order to log in to a web application or submit input data. HttpClient provides special entity class UrlEncodedFormEntity to facilitate the process.
List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("param1", "value1")); formparams.add(new BasicNameValuePair("param2", "value2")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost httppost = new HttpPost("http://localhost/handler.do"); httppost.setEntity(entity);
This UrlEncodedFormEntity instance will use the so called URL encoding to encode parameters and produce the following content:
param1=value1¶m2=value2
1.1.7.3. Content chunking Generally it is recommended to let HttpClient choose the most appropriate transfer encoding based on the properties of the HTTP message being transferred. It is possible, however, to inform HttpClient that the chunk coding is preferred by setting HttpEntity#setChunked() to true. Please note that HttpClient will use this flag as a hint only. This value well be ignored when using HTTP protocol versions that do not support chunk coding, such as HTTP/1.0.
StringEntity entity = new StringEntity("important message", "text/plain; charset=\"UTF-8\""); entity.setChunked(true); HttpPost httppost = new HttpPost("http://localhost/acrtion.do"); httppost.setEntity(entity);
Fundamentals
HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://localhost/"); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse( HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] response = httpclient.execute(httpget, handler);
HttpHost HttpHost
instance representing the connection target. instance representing the connection proxy, if used instance representing the actual HTTP request. instance representing the actual HTTP response.
HttpRequest
HttpResponse
'http.request_sent': java.lang.Boolean object representing the flag indicating whether the actual request has been fully transmitted to the connection target. For instance, in order to determine the final redirect target, one can examine the value of the http.target_host attribute after the request execution:
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://www.google.com/"); HttpResponse response = httpclient.execute(httpget, localContext); HttpHost target = (HttpHost) localContext.getAttribute( ExecutionContext.HTTP_TARGET_HOST);
Fundamentals
System.out.println("Final target: " + target); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); }
stdout >
Fundamentals
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute( ExecutionContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; httpclient.setHttpRequestRetryHandler(myRetryHandler);
10
Fundamentals
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); AtomicInteger count = new AtomicInteger(1); localContext.setAttribute("count", count); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { AtomicInteger count = (AtomicInteger) context.getAttribute("count"); request.addHeader("Count", Integer.toString(count.getAndIncrement())); } }); HttpGet httpget = new HttpGet("http://localhost/");
11
Fundamentals
for (int i = 0; i < 10; i++) { HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } }
DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); HttpGet httpget = new HttpGet("http://www.google.com/"); httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { System.out.println(request.getParams().getParameter( CoreProtocolPNames.PROTOCOL_VERSION)); System.out.println(request.getParams().getParameter( CoreProtocolPNames.HTTP_CONTENT_CHARSET)); System.out.println(request.getParams().getParameter( CoreProtocolPNames.USE_EXPECT_CONTINUE));
12
Fundamentals
System.out.println(request.getParams().getParameter( CoreProtocolPNames.STRICT_TRANSFER_ENCODING)); } });
stdout >
HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(true); System.out.println(params.getParameter( CoreProtocolPNames.PROTOCOL_VERSION)); System.out.println(params.getParameter( CoreProtocolPNames.HTTP_CONTENT_CHARSET)); System.out.println(params.getParameter( CoreProtocolPNames.USE_EXPECT_CONTINUE)); System.out.println(params.getParameter( CoreProtocolPNames.USER_AGENT));
stdout >
13
Fundamentals 'http.protocol.content-charset': defines the charset to be used per default for content body coding. This parameter expects a value of type java.lang.String. If this parameter is not set ISO-8859-1 will be used. 'http.useragent': defines the content of the User-Agent header. This parameter expects a value of type java.lang.String. If this parameter is not set, HttpClient will automatically generate a value for it. 'http.protocol.strict-transfer-encoding': defines whether responses with an invalid TransferEncoding header should be rejected. This parameter expects a value of type java.lang.Boolean. If this parameter is not set invalid Transfer-Encoding values will be ignored. 'http.protocol.expect-continue': activates Expect: 100-Continue handshake for the entity enclosing methods. The purpose of the Expect: 100-Continue handshake is to allow the client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. The use of the Expect: 100-continue handshake can result in a noticeable performance improvement for entity enclosing requests (such as POST and PUT) that require the target server's authentication. Expect: 100-continue handshake should be used with caution, as it may cause problems with HTTP servers and proxies that do not support HTTP/1.1 protocol. This parameter expects a value of type java.lang.Boolean. If this parameter is not set HttpClient will attempt to use the handshake. 'http.protocol.wait-for-continue': defines the maximum period of time in milliseconds the client should spend waiting for a 100-continue response. This parameter expects a value of type java.lang.Integer. If this parameter is not set HttpClient will wait 3 seconds for a confirmation before resuming the transmission of the request body.
14
15
Connection management 'http.connection.max-header-count': determines the maximum HTTP header count allowed. If set to a positive value, the number of HTTP headers received from the data stream exceeding this limit will cause an java.io.IOException. A negative or zero value will effectively disable the check. This parameter expects a value of type java.lang.Integer. If this parameter is not set, no limit will be enforced. 'http.connection.max-status-line-garbage': defines the maximum number of ignorable lines before we expect a HTTP response's status line. With HTTP/1.1 persistent connections, the problem arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified). Unfortunately, in some cases, this cannot be detected after the bad response, but only before the next one. So HttpClient must be able to skip those surplus lines this way. This parameter expects a value of type java.lang.Integer. 0 disallows all garbage/empty lines before the status line. Use java.lang.Integer#MAX_VALUE for unlimited number. If this parameter is not set unlimited number will be assumed.
16
Connection management
HttpRoutePlanner is an interface representing a strategy to compute a complete route to a given target
based on the execution context. HttpClient ships with two default HttpRoutePlanner implementation. ProxySelectorRoutePlanner is based on java.net.ProxySelector. By default, it will pick up the proxy settings of the JVM, either from system properties or from the browser running the application. DefaultHttpRoutePlanner implementation does not make use of any Java system properties, nor of system or browser proxy settings. It computes routes based exclusively on HTTP parameters described below.
PlainSocketFactory sf = PlainSocketFactory.getSocketFactory(); Socket socket = sf.createSocket(); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L); sf.connectSocket(socket, "locahost", 8080, null, -1, params);
17
Connection management
TrustManager easyTrustManager = new X509TrustManager() { @Override public void checkClientTrusted( X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy! } @Override public void checkServerTrusted( X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy! } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); SSLSocket socket = (SSLSocket) sf.createSocket(); socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L); sf.connectSocket(socket, "locahost", 443, null, -1, params);
Customization of SSLSocketFactory implies a certain degree of familiarity with the concepts of the SSL/TLS protocol, a detailed explanation of which is out of scope for this document. Please refer to the Java Secure Socket Extension [http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/ JSSERefGuide.html] for a detailed description of javax.net.ssl.SSLContext and related tools.
18
Connection management additional guarantees of authenticity of the server trust material. X509HostnameVerifier interface represents a strategy for hostname verification. HttpClient ships with three X509HostnameVerifier. Important: hostname verification should not be confused with SSL trust verification. StrictHostnameVerifier: The strict hostname verifier works the same way as Sun Java 1.4, Sun Java 5, Sun Java 6. It's also pretty close to IE6. This implementation appears to be compliant with RFC 2818 for dealing with wildcards. The hostname must match either the first CN, or any of the subject-alts. A wildcard can occur in the CN, and in any of the subject-alts. BrowserCompatHostnameVerifier: The hostname verifier that works the same way as Curl and Firefox. The hostname must match either the first CN, or any of the subjectalts. A wildcard can occur in the CN, and in any of the subject-alts. The only difference between BrowserCompatHostnameVerifier and StrictHostnameVerifier is that a wildcard (such as "*.foo.com") with BrowserCompatHostnameVerifier matches all subdomains, including "a.b.foo.com". AllowAllHostnameVerifier: This hostname verifier essentially turns hostname verification off. This implementation is a no-op, and never throws the javax.net.ssl.SSLException. Per default HttpClient uses BrowserCompatHostnameVerifier implementation. One can specify a different hostname verifier implementation if desired
properties such as the default port and the socket factory to be used to creating java.net.Socket instances for the given protocol. SchemeRegistry class is used to maintain a set of Schemes HttpClient can choose from when trying to establish a connection by a request URI:
Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS")); sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", sf, 443); SchemeRegistry sr = new SchemeRegistry(); sr.register(http); sr.register(https);
19
Connection management
HttpHost proxy = new HttpHost("someproxy", 8080); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
One can also instruct HttpClient to use standard JRE proxy selector to obtain proxy information:
DefaultHttpClient httpclient = new DefaultHttpClient(); ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpclient.setRoutePlanner(routePlanner);
Alternatively, one can provide a custom RoutePlanner implementation in order to have a complete control over the process of HTTP route computation:
DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setRoutePlanner(new HttpRoutePlanner() { public HttpRoute determineRoute( HttpHost target, HttpRequest request, HttpContext context) throws HttpException { return new HttpRoute(target, null, new HttpHost("someproxy", 8080), "https".equalsIgnoreCase(target.getSchemeName())); } });
20
Connection management
ManagedClientConnection acts as a wrapper for a OperatedClientConnection instance that manages
its state and controls all I/O operations on that connection. It also abstracts away socket operations and provides convenience methods for opening and updating sockets in order to establish a route. ManagedClientConnection instances are aware of their link to the connection manager that spawned them and of the fact that they must be returned back to the manager when no longer in use. ManagedClientConnection classes also implement ConnectionReleaseTrigger interface that can be used to trigger the release of the connection back to the manager. Once the connection release has been triggered the wrapped connection gets detached from the ManagedClientConnection wrapper and the OperatedClientConnection instance is returned back to the manager. Even though the service consumer still holds a reference to the ManagedClientConnection instance, it is no longer able to execute any I/O operation or change the state of the OperatedClientConnection either intentionally or unintentionally. This is an example of acquiring a connection from a connection manager:
HttpParams params = new BasicHttpParams(); Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SchemeRegistry sr = new SchemeRegistry(); sr.register(http); ClientConnectionManager connMrg = new SingleClientConnManager(params, sr); // Request new connection. This can be a long process ClientConnectionRequest connRequest = connMrg.requestConnection( new HttpRoute(new HttpHost("localhost", 80)), null); // Wait for connection up to 10 sec ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS); try { // Do useful things with the connection. // Release it when done. conn.releaseConnection(); } catch (IOException ex) { // Abort connection upon an I/O error. conn.abortConnection(); throw ex; }
The
be terminated prematurely by calling ClientConnectionRequest#abortRequest() if necessary. This will unblock the thread blocked in the ClientConnectionRequest#getConnection() method. wrapper class can be used to ensure automatic release of the underlying connection once the response content has been fully consumed. HttpClient uses this mechanism internally to achieve transparent connection release for all responses obtained from HttpClient#execute() methods:
BasicManagedEntity
connection
request
can
ClientConnectionRequest connRequest = connMrg.requestConnection( new HttpRoute(new HttpHost("localhost", 80)), null); ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS); try { BasicHttpRequest request = new BasicHttpRequest("GET", "/"); conn.sendRequestHeader(request); HttpResponse response = conn.receiveResponseHeader(); conn.receiveResponseEntity(response); HttpEntity entity = response.getEntity(); if (entity != null) { BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
21
Connection management
// Replace entity response.setEntity(managedEntity); } // Do something useful with the response // The connection will be released automatically // as soon as the response content has been consumed } catch (IOException ex) { // Abort connection upon an I/O error. conn.abortConnection(); throw ex; }
total. Per default this implementation will create no more than than 2 concurrent connections per given route and no more 20 connections in total. For many real-world applications these limits may prove too constraining, especially if they use HTTP as a transport protocol for their services. Connection limits, however, can be adjusted using HTTP parameters. This example shows how the connection pool parameters can be adjusted:
HttpParams params = new BasicHttpParams(); // Increase max total connection to 200 ConnManagerParams.setMaxTotalConnections(params, 200); // Increase default max connection per route to 20 ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20); // Increase max connections for localhost:80 to 50 HttpHost localhost = new HttpHost("locahost", 80); connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); HttpClient httpClient = new DefaultHttpClient(cm, params);
22
Connection management
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.google.com/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown();
for a given route have already been leased, a request for connection will block until a connection is released back to the pool. One can ensure the connection manager does not block indefinitely in the connection request operation by setting 'http.conn-manager.timeout' to a positive value. If the connection request cannot be serviced within the given time period ConnectionPoolTimeoutException will be thrown.
HttpParams params = new BasicHttpParams(); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); HttpClient httpClient = new DefaultHttpClient(cm, params); // URIs to perform GETs on
23
Connection management
String[] urisToGet = { "http://www.domain1.com/", "http://www.domain2.com/", "http://www.domain3.com/", "http://www.domain4.com/" }; // 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); } // 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(); }
static class GetThread extends Thread { private final HttpClient httpClient; private final HttpContext context; private final HttpGet httpget; public GetThread(HttpClient httpClient, HttpGet httpget) { this.httpClient = httpClient; this.context = new BasicHttpContext(); this.httpget = httpget; } @Override public void run() { try { HttpResponse response = this.httpClient.execute(this.httpget, this.context); HttpEntity entity = response.getEntity(); if (entity != null) { // do something useful with the entity // ... // ensure the connection gets released to the manager entity.consumeContent(); } } catch (Exception ex) { this.httpget.abort(); } } }
24
Connection management HttpClient tries to mitigate the problem by testing whether the connection is 'stale', that is no longer valid because it was closed on the server side, prior to using the connection for executing an HTTP request. The stale connection check is not 100% reliable and adds 10 to 30 ms overhead to each request execution. The only feasible solution that does not involve a one thread per socket model for idle connections is a dedicated monitor thread used to evict connections that are considered expired due to a long period of inactivity. The monitor thread can periodically call ClientConnectionManager#closeExpiredConnections() method to close all expired connections and evict closed connections from the pool. It can also optionally call ClientConnectionManager#closeIdleConnections() method to close all connections that have been idle over a given period of time.
public static class IdleConnectionMonitorThread extends Thread { private final ClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionMonitorThread(ClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }
25
Connection management
DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch(NumberFormatException ignore) { } } } HttpHost target = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) { // Keep alive for 5 seconds only return 5 * 1000; } else { // otherwise keep alive for 30 seconds return 30 * 1000; } } });
26
interface extends Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the Cookie header because some cookie specifications require that the Cookie header should include certain attributes only if they were specified in the Set-Cookie or Set-Cookie2 header.
ClientCookie
27
HTTP state management Here is an example of re-creating a standard cookie. Please note that standard compliant cookie must retain all attributes as sent by the origin server:
BasicClientCookie stdCookie = new BasicClientCookie("name", "value"); stdCookie.setVersion(1); stdCookie.setDomain(".mycompany.com"); stdCookie.setPath("/"); stdCookie.setSecure(true); // Set attributes EXACTLY as sent by the server stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1"); stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com");
Here is an example of re-creating a Set-Cookie2 compliant cookie. Please note that standard compliant cookie must retain all attributes as sent by the origin server:
BasicClientCookie2 stdCookie = new BasicClientCookie2("name", "value"); stdCookie.setVersion(1); stdCookie.setDomain(".mycompany.com"); stdCookie.setPorts(new int[] {80,8080}); stdCookie.setPath("/"); stdCookie.setSecure(true); // Set attributes EXACTLY as sent by the server stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1"); stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com"); stdCookie.setAttribute(ClientCookie.PORT_ATTR, "80,8080");
rules of parsing Set-Cookie and optionally Set-Cookie2 headers. rules of validation of parsed cookies. formatting of Cookie header for a given host, port and path of origin. HttpClient ships with several CookieSpec implementations: Netscape draft: This specification conforms to the original draft specification published by Netscape Communications. It should be avoided unless absolutely necessary for compatibility with legacy code. RFC 2109: RFC 2965. RFC 2965: Older version of the official HTTP state management specification superseded by
Browser compatibility: This implementations strives to closely mimic (mis)behavior of common web browser applications such as Microsoft Internet Explorer and Mozilla FireFox. Best match: 'Meta' cookie specification that picks up a cookie policy based on the format of cookies sent with the HTTP response. It basically aggregates all above implementations into one class.
28
HTTP state management It is strongly recommended to use the Best Match policy and let HttpClient pick up an appropriate compliance level at runtime based on the execution context.
Netscape draft. RFC 2109 (outdated strict policy). RFC 2965 (standard conformant strict policy). Best match meta-policy.
HttpClient httpclient = new DefaultHttpClient(); // force strict cookie policy per default httpclient.getParams().setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965); HttpGet httpget = new HttpGet("http://www.broken-server.com/"); // Override the default policy for this request
29
CookieSpecFactory csf = new CookieSpecFactory() { public CookieSpec newInstance(HttpParams params) { return new BrowserCompatSpec() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // Oh, I am easy } }; } }; DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCookieSpecs().register("easy", csf); httpclient.getParams().setParameter( ClientPNames.COOKIE_POLICY, "easy");
DefaultHttpClient httpclient = new DefaultHttpClient(); // Create a local instance of cookie store CookieStore cookieStore = new MyCookieStore(); // Populate cookies if needed BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setVersion(0); cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); // Set the store httpclient.setCookieStore(cookieStore);
30
'http.cookie-store': CookieStore instance represents the actual cookie store. The value of this attribute set in the local context takes precedence over the default one. The local HttpContext object can be used to customize the HTTP state management context prior to request execution or examine its state after the request has been executed:
HttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost:8080/"); HttpResponse response = httpclient.execute(httpget, localContext); CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN); System.out.println("Cookie origin: " + cookieOrigin); CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC); System.out.println("Cookie spec used: " + cookieSpec);
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/"); // Pass local context as a parameter HttpResponse response = httpclient.execute(httpget, localContext);
31
stdout >
user pwd
is a Microsoft Windows specific implementation that includes in addition to the user name / password pair a set of additional Windows specific attributes such as a name of the user domain, as in Microsoft Windows network the same user can belong to multiple domains with a different set of authorizations.
NTCredentials
stdout >
DOMAIN/user pwd
32
HTTP authentication Generate authorization string for the given set of credentials and the HTTP request in response to the actual authorization challenge. Please note authentication schemes may be stateful involving a series of challenge-response exchanges. HttpClient ships with several AuthScheme implementations: Basic: Basic authentication scheme as defined in RFC 2617. This authentication scheme is insecure, as the credentials are transmitted in clear text. Despite its insecurity Basic authentication scheme is perfectly adequate if used in combination with the TLS/SSL encryption. Digest. Digest authentication scheme as defined in RFC 2617. Digest authentication scheme is significantly more secure than Basic and can be a good choice for those applications that do not want the overhead of full transport security through TLS/SSL encryption. NTLM: NTLM is a proprietary authentication scheme developed by Microsoft and optimized for Windows platforms. NTLM is believed to be more secure than Digest. This scheme is requires an external NTLM engine to be functional. For details please refer to the NTLM_SUPPORT.txt document included with HttpClient distributions.
Please note NTLM scheme is NOT registered per default. The NTLM cannot be enabled per default due to licensing and legal reasons. For details on how to enable NTLM support please see this section.
33
HTTP authentication credentials provider one can provide a wild card (any host, any port, any realm, any scheme) instead of a concrete attribute value. The credentials provider is then expected to be able to find the closest match for a particular scope if the direct match cannot be found. HttpClient can work with any physical representation of a credentials provider that implements the CredentialsProvider interface. The default CredentialsProvider implementation called BasicCredentialsProvider is a simple implementation backed by a java.util.HashMap.
CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("somehost", AuthScope.ANY_PORT), new UsernamePasswordCredentials("u1", "p1")); credsProvider.setCredentials( new AuthScope("somehost", 8080), new UsernamePasswordCredentials("u2", "p2")); credsProvider.setCredentials( new AuthScope("otherhost", 8080, AuthScope.ANY_REALM, "ntlm"), new UsernamePasswordCredentials("u3", "p3")); System.out.println(credsProvider.getCredentials( new AuthScope("somehost", 80, "realm", "basic"))); System.out.println(credsProvider.getCredentials( new AuthScope("somehost", 8080, "realm", "basic"))); System.out.println(credsProvider.getCredentials( new AuthScope("otherhost", 8080, "realm", "basic"))); System.out.println(credsProvider.getCredentials( new AuthScope("otherhost", 8080, null, "ntlm")));
stdout >
34
HTTP authentication '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. '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. The local HttpContext object can be used to customize the HTTP authentication context prior to request execution or examine its state after the request has been executed:
HttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost:8080/"); HttpResponse response = httpclient.execute(httpget, localContext); AuthState proxyAuthState = (AuthState) localContext.getAttribute( ClientContext.PROXY_AUTH_STATE); System.out.println("Proxy auth scope: " + proxyAuthState.getAuthScope()); 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); System.out.println("Target auth scope: " + targetAuthState.getAuthScope()); System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme()); System.out.println("Target auth credentials: " + targetAuthState.getCredentials());
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope( targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host
35
HTTP authentication
Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; DefaultHttpClient httpclient = new DefaultHttpClient(); // Add as the very first interceptor in the protocol chain httpclient.addRequestInterceptor(preemptiveAuth, 0);
As NTLM connections are stateful it is generally recommended to trigger NTLM authentication using a relatively cheap method, such as GET or HEAD, and re-use the same connection to execute more expensive methods, especially those enclose a request entity, such as POST or PUT.
DefaultHttpClient httpclient = new DefaultHttpClient(); NTCredentials creds = new NTCredentials("user", "pwd", "myworkstation", "microsoft.com"); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); 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(); // 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(); if (entity1 != null) {
36
HTTP authentication
entity1.consumeContent(); } // 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(); if (entity2 != null) { entity2.consumeContent(); }
37
is the default implementation of the HttpClient interface. This class acts 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.
DefaultHttpClient
DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration( HttpResponse response, HttpContext context) { long keepAlive = super.getKeepAliveDuration(response, context); if (keepAlive == -1) { // Keep connections alive 5 seconds if a keep-alive value // has not be explicitly set by the server keepAlive = 5000; } return keepAlive; } });
also maintains a list of protocol interceptors intended for processing outgoing requests and incoming responses and provides methods for managing those interceptors. New protocol interceptors can be introduced to the protocol processor chain or removed from it if needed. Internally protocol interceptors are stored in a simple java.util.ArrayList. They are executed in the same natural order as they are added to the list.
DefaultHttpClient
DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.removeRequestInterceptorByClass(RequestUserAgent.class); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process( HttpRequest request, HttpContext context) throws HttpException, IOException { request.setHeader(HTTP.USER_AGENT, "My-own-client"); } });
is thread safe. It is recommended that the same instance of this class is reused for multiple request executions. When an instance of DefaultHttpClient is no longer needed and is
DefaultHttpClient
38
HTTP client service about to go out of scope the connection manager associated with it must be shut down by calling the ClientConnectionManager#shutdown() method.
39
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost:8080/"); HttpResponse response = httpclient.execute(httpget, localContext); HttpHost target = (HttpHost) localContext.getAttribute( ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest req = (HttpUriRequest) localContext.getAttribute( ExecutionContext.HTTP_REQUEST); System.out.println("Target host: " + target); System.out.println("Final request URI: " + req.getURI()); System.out.println("Final request method: " + req.getMethod());
40
class MyLineParser extends BasicLineParser { @Override public Header parseHeader( final CharArrayBuffer buffer) throws ParseException { try { return super.parseHeader(buffer); } catch (ParseException ex) { // Suppress ParseException exception return new BasicHeader("invalid", buffer.toString()); } } }
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.
class MyClientConnection extends DefaultClientConnection { @Override protected HttpMessageParser createResponseParser( final SessionInputBuffer buffer, final HttpResponseFactory responseFactory, final HttpParams params) { return new DefaultResponseParser( buffer, new MyLineParser(), responseFactory, params); } }
Provide a custom ClientConnectionOperator interface implementation in order to create connections of new class. Implement different socket initialization code if necessary.
41
Advanced topics
public MyClientConnectionOperator(final SchemeRegistry sr) { super(sr); } @Override public OperatedClientConnection createConnection() { return new MyClientConnection(); } }
Provide a custom ClientConnectionManager interface implementation in order to create connection operator of new class.
class MyClientConnManager extends SingleClientConnManager { public MyClientConnManager( final HttpParams params, final SchemeRegistry sr) { super(params, sr); } @Override protected ClientConnectionOperator createConnectionOperator( final SchemeRegistry sr) { return new MyClientConnectionOperator(sr); } }
42
Advanced topics
httpclient.setUserTokenHandler(new UserTokenHandler() { public Object getUserToken(HttpContext context) { return context.getAttribute("my-token"); } });
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost:8080/"); HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } Object userToken = localContext.getAttribute(ClientContext.USER_TOKEN); System.out.println(userToken);
6.2.2.1. Persistent stateful connections Please note that persistent connection that carry 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.
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpContext localContext1 = new BasicHttpContext(); HttpGet httpget1 = new HttpGet("http://localhost:8080/"); HttpResponse response1 = httpclient.execute(httpget1, localContext1); HttpEntity entity1 = response1.getEntity(); if (entity1 != null) { entity1.consumeContent(); } Principal principal = (Principal) localContext1.getAttribute( ClientContext.USER_TOKEN); HttpContext localContext2 = new BasicHttpContext(); localContext2.setAttribute(ClientContext.USER_TOKEN, principal); HttpGet httpget2 = new HttpGet("http://localhost:8080/"); HttpResponse response2 = httpclient.execute(httpget2, localContext2); HttpEntity entity2 = response2.getEntity(); if (entity2 != null) { entity2.consumeContent(); }
43