Apache HttpComponents Client is a library of components for building client side HTTP services
—
Apache HttpClient provides sophisticated connection management capabilities for efficient resource utilization, connection pooling, and performance optimization. This includes both pooled and basic connection managers with comprehensive lifecycle control.
public interface HttpClientConnectionManager {
ConnectionRequest requestConnection(HttpRoute route, Object state);
void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit);
void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws IOException;
void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException;
void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException;
void closeExpiredConnections();
void closeIdleConnections(long idletime, TimeUnit tunit);
void shutdown();
}Main interface for managing HTTP client connections with lifecycle control methods.
public interface ConnectionRequest {
HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectTimeoutException;
boolean cancel();
}Represents a request for a connection that may be fulfilled asynchronously.
public class PoolingHttpClientConnectionManager implements HttpClientConnectionManager, ConnPoolControl<HttpRoute> {
public PoolingHttpClientConnectionManager();
public PoolingHttpClientConnectionManager(HttpClientConnectionOperator httpClientConnectionOperator);
public PoolingHttpClientConnectionManager(HttpClientConnectionOperator httpClientConnectionOperator,
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
long timeToLive, TimeUnit tunit);
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry);
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
DnsResolver dnsResolver);
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory);
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
DnsResolver dnsResolver);
}Connection manager that maintains a pool of connections for reuse across multiple requests.
public void setMaxTotal(int max);
public int getMaxTotal();
public void setDefaultMaxPerRoute(int max);
public int getDefaultMaxPerRoute();
public void setMaxPerRoute(HttpRoute route, int max);
public int getMaxPerRoute(HttpRoute route);
public PoolStats getTotalStats();
public PoolStats getStats(HttpRoute route);Methods for configuring connection pool limits and retrieving statistics.
Example usage:
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); // Maximum total connections
cm.setDefaultMaxPerRoute(20); // Maximum connections per route
cm.setMaxPerRoute(new HttpRoute(new HttpHost("api.example.com")), 50);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();public void closeExpiredConnections();
public void closeIdleConnections(long idletime, TimeUnit tunit);
public void shutdown();Methods for cleaning up expired and idle connections.
// Close connections that have been idle for more than 30 seconds
cm.closeIdleConnections(30, TimeUnit.SECONDS);
// Close expired connections
cm.closeExpiredConnections();public class BasicHttpClientConnectionManager implements HttpClientConnectionManager {
public BasicHttpClientConnectionManager();
public BasicHttpClientConnectionManager(HttpClientConnectionOperator httpClientConnectionOperator);
public BasicHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry);
public BasicHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory);
public BasicHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
SchemePortResolver schemePortResolver,
DnsResolver dnsResolver);
}Simple connection manager that maintains only a single connection at a time.
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();public interface ConnectionSocketFactory {
Socket createSocket(HttpContext context) throws IOException;
Socket connectSocket(int connectTimeout, Socket sock, HttpHost host,
InetSocketAddress remoteAddress, InetSocketAddress localAddress,
HttpContext context) throws IOException;
}Interface for creating and configuring connection sockets.
public class PlainConnectionSocketFactory implements ConnectionSocketFactory {
public static PlainConnectionSocketFactory getSocketFactory();
public Socket createSocket(HttpContext context) throws IOException;
public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host,
InetSocketAddress remoteAddress, InetSocketAddress localAddress,
HttpContext context) throws IOException;
}Factory for creating plain (non-SSL) connections.
public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory {
public static SSLConnectionSocketFactory getSocketFactory();
public static SSLConnectionSocketFactory getSystemSocketFactory();
public SSLConnectionSocketFactory(SSLContext sslContext);
public SSLConnectionSocketFactory(SSLContext sslContext, HostnameVerifier hostnameVerifier);
public SSLConnectionSocketFactory(SSLContext sslContext, String[] supportedProtocols,
String[] supportedCipherSuites, HostnameVerifier hostnameVerifier);
}Factory for creating SSL/TLS connections.
Example configuration:
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSystemSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);public class PoolStats {
public int getLeased();
public int getPending();
public int getAvailable();
public int getMax();
}Statistics for connection pool state.
Example usage:
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// ... perform requests ...
PoolStats totalStats = cm.getTotalStats();
System.out.println("Leased connections: " + totalStats.getLeased());
System.out.println("Pending requests: " + totalStats.getPending());
System.out.println("Available connections: " + totalStats.getAvailable());
System.out.println("Max connections: " + totalStats.getMax());public interface ManagedHttpClientConnection extends HttpClientConnection, HttpInetConnection {
String getId();
void bind(Socket socket) throws IOException;
Socket getSocket();
SSLSession getSSLSession();
}Interface representing a managed HTTP client connection.
public interface ConnectionRequest {
HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectTimeoutException;
boolean cancel();
}Represents an asynchronous request for a connection.
public final class HttpRoute implements Cloneable {
public HttpRoute(HttpHost target);
public HttpRoute(HttpHost target, InetAddress localAddress, HttpHost proxy, boolean secure);
public HttpHost getTargetHost();
public HttpHost getProxyHost();
public int getHopCount();
public HttpHost getHopTarget(int hop);
public boolean isSecure();
public boolean isTunnelled();
public boolean isLayered();
}Represents the route that a request will take to reach the target server.
public interface RouteInfo {
HttpHost getTargetHost();
HttpHost getProxyHost();
int getHopCount();
HttpHost getHopTarget(int hop);
boolean isSecure();
TunnelType getTunnelType();
LayerType getLayerType();
}Information about the route to a target host.
public interface ConnectionKeepAliveStrategy {
long getKeepAliveDuration(HttpResponse response, HttpContext context);
}Strategy for determining connection keep-alive duration.
Example implementation:
ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
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")) {
return Long.parseLong(value) * 1000;
}
}
return 5 * 1000; // Default to 5 seconds
}
};
CloseableHttpClient httpClient = HttpClients.custom()
.setKeepAliveStrategy(keepAliveStrategy)
.build();public interface ConnPoolControl<T> {
void setMaxTotal(int max);
int getMaxTotal();
void setDefaultMaxPerRoute(int max);
int getDefaultMaxPerRoute();
void setMaxPerRoute(T route, int max);
int getMaxPerRoute(T route);
PoolStats getTotalStats();
PoolStats getStats(T route);
}Interface for controlling connection pool configuration.
Install with Tessl CLI
npx tessl i tessl/maven-org-apache-httpcomponents--httpclient