<
meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<
title>Chapter
2. Connection management<
/title><
link rel="stylesheet" href="css/hc-tutorial.css" type="text/css"><
meta name="generator" content="DocBook XSL-NS Stylesheets V1.73.2"><
link rel="start" href="index.html" title="HttpClient Tutorial"><
link rel="up" href="index.html" title="HttpClient Tutorial"><
link rel="prev" href="fundamentals.html" title="Chapter 1. Fundamentals"><
link rel="next" href="statemgmt.html" title="Chapter 3. HTTP state management"><
/head><
body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><
div xmlns:fo
="http://www.w3.org/1999/XSL/Format" class="banner"><
a class="bannerLeft" href="http://www.apache.org/" title="Apache Software Foundation"><
img style="border:none;" src="images/asf_logo_wide.gif"><
/a><
a class="bannerRight" href="http://hc.apache.org/httpcomponents-core/" title="Apache HttpComponents Core"><
img style="border:none;" src="images/hc_logo.png"><
/a><
div class="clear"><
/div><
/div><
div class="navheader"><
table width="100%" summary="Navigation header"><
tr><
th colspan="3" align="center">Chapter
2. Connection management<
/th><
/tr><
tr><
td width="20%" align="left"><
a accesskey="p" href="fundamentals.html">Prev<
/a> <
/td><
th width="60%" align="center"> <
/th><
td width="20%" align="right"> <
a accesskey="n" href="statemgmt.html">Next<
/a><
/td><
/tr><
/table><
hr><
/div><
div class="chapter" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title"><
a name="connmgmt"><
/a>Chapter
2. Connection management<
/h2><
/div><
/div><
/div>
<
p>HttpClient has a complete control over the process of connection initialization and
termination as well as I/O operations on active connections. However various aspects of
connection operations can be controlled using a number of parameters.<
/p>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e391"><
/a>
2.1. Connection parameters<
/h2><
/div><
/div><
/div>
<
p>These are parameters that can influence connection operations:<
/p>
<
div class="itemizedlist"><
ul type="disc"><
li>
<
b>
'http.socket.timeout': <
/b>
defines the socket timeout
(<
code class="literal">SO_TIMEOUT<
/code>
) in
milliseconds, which is the timeout for waiting for data or, put differently,
a maximum period inactivity between two consecutive data packets). A timeout
value of zero is interpreted as an infinite timeout. This parameter expects
a
value of
type <
code class="classname">java.
lang.Integer<
/code>. If this parameter
is not set read operations will not time out (infinite timeout).
<
b>
'http.tcp.nodelay': <
/b>
determines whether Nagle's algorithm is to be used. The Nagle's algorithm
tries to conserve bandwidth by minimizing the number of segments that are
sent. When applications wish to decrease network latency and increase
performance, they can disable Nagle's algorithm (that is enable
<code class="literal">TCP_NODELAY</code>. Data will be sent earlier, at the cost
of an increase in bandwidth consumption. This parameter expects a value of
type <code class="classname">java.lang.Boolean</code>. If this parameter is not,
<code class="literal">TCP_NODELAY</code> will be enabled (no delay).
</p>
<p>
<b>'http.socket.buffer-size': </b>
determines the size of the internal socket buffer used to buffer data
while receiving / transmitting HTTP messages. This parameter expects a value
of type <code class="classname">java.lang.Integer</code>. If this parameter is not
set HttpClient will allocate 8192 byte socket buffers.
</p>
<p>
<b>'http.socket.linger': </b>
sets <code class="literal">SO_LINGER</code> with the specified linger time in
seconds. The maximum timeout value is platform specific. Value 0 implies
that the option is disabled. Value -1 implies that the JRE default is used.
The setting only affects the socket close operation. If this parameter is
not set value -1 (JRE default) will be assumed.
</p>
<p>
<b>'http.connection.timeout': </b>
determines the timeout in milliseconds until a connection is established.
A timeout value of zero is interpreted as an infinite timeout. This
parameter expects a value of type <code class="classname">java.lang.Integer</code>.
If this parameter is not set connect operations will not time out (infinite
timeout).
</p>
<p>
<b>'http.connection.stalecheck': </b>
determines whether stale connection check is to be used. Disabling stale
connection check may result in a noticeable performance improvement (the
check can cause up to 30 millisecond overhead per request) at the risk of
getting an I/O error when executing a request over a connection that has
been closed at the server side. This parameter expects a value of type
<code class="classname">java.lang.Boolean</code>. For performance critical
operations the check should be disabled. If this parameter is not set the
stale connection will be performed before each request execution.
</p>
<p>
<b>'http.connection.max-line-length': </b>
determines the maximum line length limit. If set to a positive value, any
HTTP line exceeding this limit will cause an
<code class="exceptionname">java.io.IOException</code>. A negative or zero
value will effectively disable the check. This parameter expects a value of
type <code class="classname">java.lang.Integer</code>. If this parameter is not set,
no limit will be enforced.
</p>
<p>
<b>'http.connection.max-header-count': </b>
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 <code class="exceptionname">java.io.IOException</code>.
A negative or zero value will effectively disable the check. This parameter
expects a value of type <code class="classname">java.lang.Integer</code>. If this
parameter is not set, no limit will be enforced.
</p>
<p>
<b>'http.connection.max-status-line-garbage': </b>
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
<
code class="literal">Content-Length<
/code>
(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 <
code class="constant">java.
lang.Integer#MAX_VALUE<
/code>
for unlimited
number. If this parameter is not set unlimited number will be
assumed.
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e438"><
/a>
2.2. Connection persistence<
/h2><
/div><
/div><
/div>
<
p>The process of establishing a connection from one host to another is quite complex and
involves multiple packet exchanges between two endpoints, which can be quite time
consuming. The overhead of connection handshaking can be significant, especially for
small HTTP messages. One can achieve a much higher data throughput if open connections
can be re-used to execute
multiple requests.<
/p>
<
p>HTTP
/1.1 states that HTTP connections can be re-used
for multiple requests per
default. HTTP/1.0 compliant endpoints can also use similar mechanism to explicitly
communicate their preference to keep connection alive and use it for multiple requests.
HTTP agents can also keep idle connections alive for a certain period time in case a
connection to the same target host may be needed for subsequent requests. The ability to
keep connections alive is usually refered to as connection persistence. HttpClient fully
supports connection persistence.<
/p>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e442"><
/a>
2.3. HTTP connection routing<
/h2><
/div><
/div><
/div>
<
p>HttpClient is capable of establishing connections to the
target host either directly
or via a route that may involve multiple intermediate connections also referred to as
hops. HttpClient differentiates connections of a route into plain, tunneled and layered.
The use of multiple intermediate proxies to tunnel connections to the target host is
referred to as proxy chaining.<
/p>
<
p>Plain routes are established by connecting to the
target or the first and only proxy.
Tunnelled routes are established by connecting to the first and tunnelling through a
chain of proxies to the target. Routes without a proxy cannot be tunnelled. Layered
routes are established by layering a protocol over an existing connection. Protocols can
only be layered over a tunnel to the target, or over a direct connection without
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e446"><
/a>2.3.1. Route computation<
/h3><
/div><
/div><
/div>
<
p><
code class="interfacename">RouteInfo<
/code> interface represents information about a
definitive route to a target host involving one or more intermediate steps or hops.
<
code class="classname">HttpRoute<
/code> is a concrete implementation of
<
code class="interfacename">RouteInfo<
/code>, which cannot be changed
(is
immutable
). <
code class="classname">HttpTracker<
/code> is a mutable
<
code class="interfacename">RouteInfo<
/code> implementation used internally by
HttpClient to track the remaining hops to the ultimate route target.
<
code class="classname">HttpTracker<
/code> can be updated after a successful execution
of the next hop towards the route
target. <
code class="classname">HttpRouteDirector<
/code>
is a helper class that can be used to compute the next step in a route. This class
is used internally by HttpClient.<
/p>
<
p><
code class="interfacename">HttpRoutePlanner<
/code> 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
<
code class="interfacename">HttpRoutePlanner<
/code> implementation.
<
code class="classname">ProxySelectorRoutePlanner<
/code> is based on
<
code class="classname">java.net.ProxySelector<
/code>. By default, it will pick up the
proxy settings of the JVM, either from system properties or from the browser running
the application. <
code class="classname">DefaultHttpRoutePlanner<
/code> 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.<
/p>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e462"><
/a>2.3.2. Secure HTTP connections<
/h3><
/div><
/div><
/div>
<
p>HTTP connections can be considered secure if information transmitted between two
connection endpoints cannot be read or tampered with by an unauthorized third party.
The SSL/TLS protocol is the most widely used technique to ensure HTTP transport
security. However, other encryption techniques could be employed as well. Usually,
HTTP transport is layered over the SSL
/TLS encrypted connection.<
/p>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e465"><
/a>
2.4. HTTP route parameters<
/h2><
/div><
/div><
/div>
<
p>These are parameters that can influence route computation:<
/p>
<
div class="itemizedlist"><
ul type="disc"><
li>
<
b>
'http.route.default-proxy': <
/b>
defines a proxy host to be used by default route planners that do not make
use of JRE settings. This parameter expects a value of type
<
code class="classname">HttpHost<
/code>. If this parameter is not set direct
connections to the target will be attempted.
<
b>
'http.route.local-address': <
/b>
defines a local address to be used by all default route planner. On
machines with multiple network interfaces, this parameter can be used to
select the network interface from which the connection originates. This
parameter expects a value of type
<
code class="classname">java.net.InetAddress<
/code>. If this parameter is not
set a default local address will be used automatically.
<
b>
'http.route.forced-route': <
/b>
defines an forced route to be used by all default route planner. Instead
of computing a route, the given forced route will be returned, even if it
points to a completely different target host. This parameter expects a value
of
type <
code class="classname">HttpRoute<
/code>.
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e484"><
/a>
2.5. Socket factories<
/h2><
/div><
/div><
/div>
<
p>HTTP connections make use of a <
code class="classname">java.net.Socket<
/code>
object
internally to handle transmission of data across the wire. They, however, rely on
<
code class="interfacename">SocketFactory<
/code> interface to create, initialize and
connect sockets. This enables the users of HttpClient to provide application specific
socket initialization
code at runtime. <
code class="classname">PlainSocketFactory<
/code> is the
default factory
for creating and initializing plain
(unencrypted
) sockets.<
/p>
<
p>The process of creating a socket and that of connecting it to a host are decoupled, so
that the socket could be closed while being blocked in the connect operation.<
/p>
<
pre class="programlisting">
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);
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e492"><
/a>2.5.1. Secure socket layering<
/h3><
/div><
/div><
/div>
<
p><
code class="interfacename">LayeredSocketFactory<
/code> is an extension of
<
code class="interfacename">SocketFactory<
/code> interface. Layered socket factories
are capable of creating sockets that are layered over an existing plain socket.
Socket layering is used primarily for creating secure sockets through proxies.
HttpClient ships with SSLSocketFactory that implements SSL/TLS layering. Please note
HttpClient does not use any custom encryption functionality. It is fully reliant on
standard Java Cryptography
(JCE
) and Secure Sockets
(JSEE
) extensions.<
/p>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e497"><
/a>2.5.2. SSL
/TLS customization<
/h3><
/div><
/div><
/div>
<
p>HttpClient makes use of SSLSocketFactory to create SSL connections.
<
code class="classname">SSLSocketFactory<
/code> allows
for a high degree of
customization. It can take an instance of
<
code class="interfacename">javax.net.ssl.SSLContext<
/code> as a parameter and use
it to create custom configured SSL connections.<
/p>
<
pre class="programlisting">
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);
<
p>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 <
a class="ulink" href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html" target="_top">Java Secure Socket Extension<
/a>
for a detailed description of
<
code class="interfacename">javax.net.ssl.SSLContext<
/code> and related
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e506"><
/a>2.5.3. Hostname verification<
/h3><
/div><
/div><
/div>
<
p>In addition to the trust verification and the client authentication performed on
the SSL/TLS protocol level, HttpClient can optionally verify whether the target
hostname matches the names stored inside the server's X.509 certificate, once the
connection has been established. This verification can provide 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.</p>
<div class="itemizedlist"><ul type="disc"><li>
<p>
<b><code class="classname">StrictHostnameVerifier</code>: </b>
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.
<
b><
code class="classname">BrowserCompatHostnameVerifier<
/code>: <
/b>
The hostname verifier that works the same way as Curl and Firefox. 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. The only
difference between <
code class="classname">BrowserCompatHostnameVerifier<
/code>
and <
code class="classname">StrictHostnameVerifier<
/code> is that a wildcard
(such as "*.foo.com") with
<
code class="classname">BrowserCompatHostnameVerifier<
/code> matches all
subdomains, including "a.b.foo.com".
<
b><
code class="classname">AllowAllHostnameVerifier<
/code>: <
/b>
This hostname verifier essentially turns hostname verification off.
This implementation is a no-op, and never throws the
<
code class="exceptionname">javax.net.ssl.SSLException<
/code>.
<
p>Per default HttpClient uses <
code class="classname">BrowserCompatHostnameVerifier<
/code>
implementation. One can specify a different hostname verifier implementation if
<
pre class="programlisting">
SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e532"><
/a>
2.6. Protocol schemes<
/h2><
/div><
/div><
/div>
<
p><
code class="classname">Scheme<
/code>
class represents a protocol
scheme such as
"http" or
"https" and contains a number of protocol properties such as the default port and the
socket factory to be used to creating <
code class="classname">java.net.Socket<
/code> instances
for the given protocol. <
code class="classname">SchemeRegistry<
/code>
class is used to maintain
a set of <
code class="classname">Scheme<
/code>s HttpClient can choose from when trying to
establish a connection by a request URI:<
/p>
<
pre class="programlisting">
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);
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e540"><
/a>
2.7. HttpClient proxy configuration<
/h2><
/div><
/div><
/div>
<
p>Even though HttpClient is aware of complex routing scemes and proxy chaining, it
supports only simple direct or one hop proxy connections out of the box.<
/p>
<
p>The simplest way to tell HttpClient to connect to the
target host via a proxy is by
setting the default proxy parameter:<
/p>
<
pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpHost proxy = new HttpHost("someproxy", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
<
p>One can also instruct HttpClient to use standard JRE proxy selector to obtain proxy
<
pre class="programlisting">
DefaultHttpClient httpclient = new DefaultHttpClient();
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
httpclient.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
httpclient.setRoutePlanner(routePlanner);
<
p>Alternatively, one can provide a custom <
code class="interfacename">RoutePlanner<
/code>
implementation in order to have a complete control over the process of HTTP route
<
pre class="programlisting">
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()));
}
});
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e550"><
/a>
2.8. HTTP connection managers<
/h2><
/div><
/div><
/div>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e552"><
/a>2.8.1. Connection operators<
/h3><
/div><
/div><
/div>
<
p>Operated connections are client side connections whose underlying socket or its
state can be manipulated by an external entity, usually referred to as a connection
operator. <
code class="interfacename">OperatedClientConnection<
/code> interface extends
<
code class="interfacename">HttpClientConnection<
/code> interface and define
additional methods to manage connection socket. The
<
code class="interfacename">ClientConnectionOperator<
/code> interface represents a
strategy
for creating <
code class="interfacename">OperatedClientConnection<
/code>
instances and updating the underlying socket of those objects. Implementations will
most likely make use <
code class="interfacename">SocketFactory<
/code>s to create
<
code class="classname">java.net.Socket<
/code> instances. The
<
code class="interfacename">ClientConnectionOperator<
/code> interface enables the
users of HttpClient to provide a custom strategy for connection operators as well as
an ability to provide alternative implementation of the
<
code class="interfacename">OperatedClientConnection<
/code> interface.<
/p>
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e563"><
/a>2.8.2. Managed connections and connection managers<
/h3><
/div><
/div><
/div>
<
p>HTTP connections are complex, stateful, thread-unsafe objects which need to be
properly managed to function correctly. HTTP connections can only be used by one
execution thread at a time. HttpClient employs a special entity to manage access to
HTTP connections called HTTP connection manager and represented by the
<
code class="interfacename">ClientConnectionManager<
/code> interface. The purpose of
an HTTP connection manager is to serve as a factory for new HTTP connections, manage
persistent connections and synchronize access to persistent connections making sure
that only one thread can have access to a connection at a time.<
/p>
<
p>Internally HTTP connection managers work with instances of
<
code class="interfacename">OperatedClientConnection<
/code>, but they hands out
instances of <
code class="interfacename">ManagedClientConnection<
/code> to the service
consumers. <
code class="interfacename">ManagedClientConnection<
/code> acts as a wrapper
for a <
code class="interfacename">OperatedClientConnection<
/code> 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.
<
code class="interfacename">ManagedClientConnection<
/code> 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.
<
code class="interfacename">ManagedClientConnection<
/code> classes also implement
<
code class="interfacename">ConnectionReleaseTrigger<
/code> 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
<
code class="interfacename">ManagedClientConnection<
/code> wrapper and the
<
code class="interfacename">OperatedClientConnection<
/code> instance is returned
back to the manager. Even though the service consumer still holds a reference to the
<
code class="interfacename">ManagedClientConnection<
/code> instance, it is no longer
able to execute any I/O operation or change the state of the
<
code class="interfacename">OperatedClientConnection<
/code> either intentionally or
<
p>This is an example of acquiring a connection from a connection manager:<
/p>
<
pre class="programlisting">
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;
}
<
p>The connection request can be terminated prematurely by calling
<
code class="methodname">ClientConnectionRequest#abortRequest
()<
/code> if necessary.
This will unblock the thread blocked in the
<
code class="methodname">ClientConnectionRequest#getConnection
()<
/code>
method.<
/p>
<
p><
code class="classname">BasicManagedEntity<
/code> 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
<
code class="methodname">HttpClient#execute
()<
/code> methods:<
/p>
<
pre class="programlisting">
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);
// 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;
}
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e588"><
/a>2.8.3. Simple connection manager<
/h3><
/div><
/div><
/div>
<
p><
code class="classname">SingleClientConnManager<
/code> is a simple connection manager that
maintains only one connection at a time. Even though this class is thread-safe it
ought to be used by one execution thread only.
<
code class="classname">SingleClientConnManager<
/code> will make an effort to reuse the
connection for subsequent requests with the same route. It will, however, close the
existing connection and open it for the given route, if the route of the persistent
connection does not match that of the connection request. If the connection has been
already been allocated
<
code class="exceptionname">java.
lang.IllegalStateException<
/code> is thrown.<
/p>
<
p><
code class="classname">SingleClientConnManager<
/code> is used by HttpClient per
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e596"><
/a>2.8.4. Pooling connection manager<
/h3><
/div><
/div><
/div>
<
p><
code class="classname">ThreadSafeClientConnManager<
/code> is a more complex
implementation that manages a pool of client connections and is able to service
connection requests from multiple execution threads. Connections are pooled on a per
route basis. A request for a route which already the manager has persistent
connections for available in the pool will be services by leasing a connection from
the pool rather than creating a brand new connection.<
/p>
<
p><
code class="classname">ThreadSafeClientConnManager<
/code> maintains a maximum limit of
connection on a per route basis and in 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.<
/p>
<
p>This example shows how the connection pool parameters can be adjusted:<
/p>
<
pre class="programlisting">
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);
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h3 class="title"><
a name="d4e604"><
/a>2.8.5. Connection manager shutdown<
/h3><
/div><
/div><
/div>
<
p>When an HttpClient instance is no longer needed and is about to go out of
scope it
is important to shut down its connection manager to ensure that all connections kept
alive by the manager get closed and system resources allocated by those connections
<
pre class="programlisting">
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();
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e608"><
/a>
2.9. Connection management parameters<
/h2><
/div><
/div><
/div>
<
p>These are parameters that be used to customize standard HTTP connection manager
<
div class="itemizedlist"><
ul type="disc"><
li>
<
b>
'http.conn-manager.timeout': <
/b>
defines the timeout in milliseconds used when retrieving an instance of
<
code class="interfacename">ManagedClientConnection<
/code> from the
<
code class="interfacename">ClientConnectionManager<
/code> This parameter
expects a
value of
type <
code class="classname">java.
lang.Long<
/code>. If this
parameter is not set connection requests will not time out (infinite
timeout).
<
b>
'http.conn-manager.max-per-route': <
/b>
defines the maximum number of connections per route. This limit is
interpreted by client connection managers and applies to individual manager
instances. This parameter expects a value of type
<
code class="interfacename">ConnPerRoute<
/code>.
<
b>
'http.conn-manager.max-total': <
/b>
defines the maximum number of connections in total. This limit is
interpreted by client connection managers and applies to individual manager
instances. This parameter expects a value of type
<
code class="classname">java.
lang.Integer<
/code>.
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e629"><
/a>
2.10. Multithreaded request execution<
/h2><
/div><
/div><
/div>
<
p>When equipped with a pooling connection manager such as ThreadSafeClientConnManager
HttpClient can be used to execute multiple requests simultaneously using multiple
threads of execution.<
/p>
<
p><
code class="classname">ThreadSafeClientConnManager<
/code> will allocate connections based on
its configuration. If all connections 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 <
code class="literal">
'http.conn-manager.timeout'<
/code> to a positive
value.
If the connection request cannot be serviced within the given time period
<
code class="exceptionname">ConnectionPoolTimeoutException<
/code> will be thrown.<
/p>
<
pre class="programlisting">
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
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();
}
<
pre class="programlisting">
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();
}
}
}
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e638"><
/a>
2.11. Connection eviction policy<
/h2><
/div><
/div><
/div>
<
p>One of the major shortcoming of the classic blocking I
/O model is that the network
socket can react to I/O events only when blocked in an I/O operation. When a connection
is released back to the manager, it can be kept alive however it is unable to monitor
the status of the socket and react to any I/O events. If the connection gets closed on
the server side, the client side connection is unable to detect the change in the
connection state and react appropriately by closing the socket on its end.<
/p>
<
p>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
<
code class="methodname">ClientConnectionManager#closeExpiredConnections
()<
/code>
method to
close all expired connections and evict closed connections from the pool. It can also
optionally call <
code class="methodname">ClientConnectionManager#closeIdleConnections
()<
/code>
method to close all connections that have been idle over a given period of time.<
/p>
<
pre class="programlisting">
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();
}
}
}
<
div class="section" lang="en"><
div class="titlepage"><
div><
div><
h2 class="title" style="clear: both"><
a name="d4e645"><
/a>
2.12. Connection keep alive strategy<
/h2><
/div><
/div><
/div>
<
p>The HTTP specification does not specify how long a persistent connection may be and
should be kept alive. Some HTTP servers use non-standard <
code class="literal">Keep-Alive<
/code>
header to communicate to the client the period of time in seconds they intend to keep
the connection alive on the server side. HttpClient makes use of this information if
available. If the <
code class="literal">Keep-Alive<
/code> header is not present in the response,
HttpClient assumes the connection can be kept alive indefinitely. However, many HTTP
servers out there are configured to drop persistent connections after a certain period
of inactivity in order to conserve system resources, quite often without informing the
client. In case the default strategy turns out to be too optimistic, one may want to
provide a custom keep-alive strategy.<
/p>
<
pre class="programlisting">
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;
}
}
});
<
/div><
div class="navfooter"><
hr><
table width="100%" summary="Navigation footer"><
tr><
td width="40%" align="left"><
a accesskey="p" href="fundamentals.html">Prev<
/a> <
/td><
td width="20%" align="center"> <
/td><
td width="40%" align="right"> <
a accesskey="n" href="statemgmt.html">Next<
/a><
/td><
/tr><
tr><
td width="40%" align="left" valign="top">Chapter
1. Fundamentals <
/td><
td width="20%" align="center"><
a accesskey="h" href="index.html">Home<
/a><
/td><
td width="40%" align="right" valign="top"> Chapter
3. HTTP state management<
/td><
/tr><
/table><
/div><
/body><
/html>