The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, weβll go over the basics of connection management within HttpClient 5
Weβll cover the use of BasicHttpClientConnectionManager and PoolingHttpClientConnectionManager to enforce a safe, protocol-compliant and efficient use of HTTP connections.
2. The BasicHttpClientConnectionManager for a Low-Level, Single-Threaded Connection
The BasicHttpClientConnectionManager is available since HttpClient 4.3.3 as the simplest implementation of an HTTP connection manager.
We use it to create and manage a single connection that only one thread can use at a time.
Further reading:
Advanced Apache HttpClient Configuration
Apache HttpClient - Send Custom Cookie
Example 2.1. Getting a Connection Request for a Low-Level Connection (HttpClientConnection)
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
The lease method gets from the manager a pool of connections for a specific route to connect to. The route parameter specifies a route of βproxy hopsβ to the target host, or the target host itself.
It is possible to run a request using an HttpClientConnection directly. However, keep in mind this low-level approach is verbose and difficult to manage. Low-level connections are useful to access socket and connection data such as timeouts and target host information. But for standard executions, the HttpClient is a much easier API to work against.
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
3. Using the PoolingHttpClientConnectionManager to Get and Manage a Pool of Multithreaded Connections
The ClientConnectionPoolManager maintains a pool of ManagedHttpClientConnections and is able to service connection requests from multiple execution threads. The default size of the pool of concurrent connections that can be open by the manager is five for each route or target host and 25 for total open connections.
First, letβs take a look at how to set up this connection manager on a simple HttpClient:
Example 3.1. Setting the PoolingHttpClientConnectionManager on an HttpClient
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
client.execute(new HttpGet("https://www.baeldung.com"));
assertTrue(poolingConnManager.getTotalStats().getLeased() == 1);
Next, letβs see how the same connection manager can be used by two HttpClients running in two different threads:
Example 3.2. Using Two HttpClients to Connect to One Target Host Each
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client1 = HttpClients.custom()
.setConnectionManager(connManager)
.build();
CloseableHttpClient client2 = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
Notice that weβre using a very simple custom thread implementation:
Example 3.3. Custom Thread Executing a GET Request
public class MultiHttpClientConnThread extends Thread {
private CloseableHttpClient client;
private HttpGet get;
// standard constructors
public void run(){
try {
HttpEntity entity = client.execute(get).getEntity();
EntityUtils.consume(entity);
} catch (ClientProtocolException ex) {
} catch (IOException ex) {
}
}
}
4. Configure the Connection Manager
The defaults of the pooling connection manager are well chosen. But, depending on our use case, they may be too small.
So, letβs see how we can configure
- the total number of connections
- the maximum number of connections per (any) route
- the maximum number of connections per a single, specific route
Example 4.1. Increasing the Number of Connections That Can Be Open and Managed Beyond the default Limits
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
HttpHost host = new HttpHost("www.baeldung.com", 80);
connManager.setMaxPerRoute(new HttpRoute(host), 5);
Letβs recap the API:
- setMaxTotal(int max) β Set the maximum number of total open connections
- setDefaultMaxPerRoute(int max) β Set the maximum number of concurrent connections per route, which is two by default
- setMaxPerRoute(int max) β Set the total number of concurrent connections to a specific route, which is two by default
So, without changing the default, weβre going to reach the limits of the connection manager quite easily.
Letβs see what that looks like:
Example 4.2. Using Threads to Execute Connections
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread4 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread5 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread6 = new MultiHttpClientConnThread(client, get, connManager);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
Remember that the per host connection limit is five by default. So, in this example, we want six threads to make six requests to the same host, but only three connections will be allocated in parallel.
Letβs take a look at the logs.
We have six threads running but only five leased connections:
15:37:02.631 [Thread-0] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Leased Connections = 0
15:37:02.631 [Thread-5] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Leased Connections = 0
15:37:02.631 [Thread-1] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Leased Connections = 0
15:37:02.631 [Thread-3] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Leased Connections = 0
15:37:02.633 [Thread-5] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Available Connections = 0
15:37:02.633 [Thread-1] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Available Connections = 0
15:37:02.631 [Thread-4] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Leased Connections = 0
15:37:02.631 [Thread-2] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Leased Connections = 0
15:37:02.633 [Thread-4] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Available Connections = 0
15:37:02.633 [Thread-0] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Available Connections = 0
15:37:02.633 [Thread-3] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Available Connections = 0
15:37:02.633 [Thread-2] INFO c.b.h.conn.MultiHttpClientConnThread - Before - Available Connections = 0
15:37:02.949 [Thread-1] INFO c.b.h.conn.MultiHttpClientConnThread - After - Leased Connections = 5
15:37:02.949 [Thread-2] INFO c.b.h.conn.MultiHttpClientConnThread - After - Leased Connections = 5
15:37:02.949 [Thread-5] INFO c.b.h.conn.MultiHttpClientConnThread - After - Leased Connections = 5
15:37:02.949 [Thread-2] INFO c.b.h.conn.MultiHttpClientConnThread - After - Available Connections = 5
15:37:02.949 [Thread-3] INFO c.b.h.conn.MultiHttpClientConnThread - After - Leased Connections = 5
15:37:02.949 [Thread-1] INFO c.b.h.conn.MultiHttpClientConnThread - After - Available Connections = 5
15:37:02.949 [Thread-5] INFO c.b.h.conn.MultiHttpClientConnThread - After - Available Connections = 5
15:37:02.949 [Thread-3] INFO c.b.h.conn.MultiHttpClientConnThread - After - Available Connections = 5
15:37:02.953 [Thread-0] INFO c.b.h.conn.MultiHttpClientConnThread - After - Leased Connections = 5
15:37:02.953 [Thread-0] INFO c.b.h.conn.MultiHttpClientConnThread - After - Available Connections = 5
15:37:03.004 [Thread-4] INFO c.b.h.conn.MultiHttpClientConnThread - After - Leased Connections = 1
15:37:03.004 [Thread-4] INFO c.b.h.conn.MultiHttpClientConnThread - After - Available Connections = 5
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
5. Connection Keep-Alive Strategy
According to the HttpClient 5.2: βIf the Keep-Alive header is not present in the response, HttpClient assumes the connection can be kept alive for 3 minutes.β
To get around this and be able to manage dead connections, we need a customized strategy implementation and to build it into the HttpClient.
Example 5.1. A Custom Keep-Alive Strategy
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
Args.notNull(response, "HTTP response");
final Iterator<HeaderElement> it = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE);
final HeaderElement he = it.next();
final String param = he.getName();
final String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return TimeValue.ofSeconds(Long.parseLong(value));
} catch (final NumberFormatException ignore) {
}
}
return TimeValue.ofSeconds(5);
}
};
This strategy will first try to apply the hostβs Keep-Alive policy stated in the header. If that information is not present in the response header, it will keep alive connections for five seconds.
Now letβs create a client with this custom strategy:
PoolingHttpClientConnectionManager connManager
= new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setKeepAliveStrategy(myStrategy)
.setConnectionManager(connManager)
.build();
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
6. Connection Persistence/Reuse
The HTTP/1.1 Spec states that we can reuse connections if they have not been closed. This is known as connection persistence.
Once the manager releases a connection, it stays open for reuse.
When using a BasicHttpClientConnectionManager, which can only mange a single connection, the connection must be released before it is leased back again:
Example 6.1. BasicHttpClientConnectionManager Connection Reuse
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
final HttpContext context = new BasicHttpContext();
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
final ConnectionEndpoint endpoint = connRequest.get(Timeout.ZERO_MILLISECONDS);
connMgr.connect(endpoint, Timeout.ZERO_MILLISECONDS, context);
connMgr.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connMgr)
.build();
HttpGet httpGet = new HttpGet("https://www.example.com");
client.execute(httpGet, context, response -> response);
Letβs take a look at what happens.
Notice that we use a low-level connection first, just so that we have full control over when we release the connection, and then a normal higher-level connection with an HttpClient.
The complex low-level logic is not very relevant here. The only thing we care about is the releaseConnection call. That releases the only available connection and allows it to be reused.
Then the client runs the GET request again with success.
If we skip releasing the connection, we will get an IllegalStateException from the HttpClient:
java.lang.IllegalStateException: Connection is still allocated
at o.a.h.u.Asserts.check(Asserts.java:34)
at o.a.h.i.c.BasicHttpClientConnectionManager.getConnection
(BasicHttpClientConnectionManager.java:248)
Note that the existing connection isnβt closed, just released and then reused by the second request.
In contrast to the above example, the PoolingHttpClientConnectionManager allows connection reuse transparently without the need to release a connection implicitly:
Example 6.2. PoolingHttpClientConnectionManager: Reusing Connections With Threads
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(6);
connManager.setMaxTotal(6);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new MultiHttpClientConnThread(client, get, connManager);
}
for (MultiHttpClientConnThread thread : threads) {
thread.start();
}
for (MultiHttpClientConnThread thread : threads) {
thread.join(1000);
}
The example above has 10 threads running 10 requests but only sharing 6 connections.
Of course, this example relies on the serverβs Keep-Alive timeout. To make sure the connections donβt die before reuse, we should configure the client with a Keep-Alive strategy (See Example 5.1.).
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
7. Configuring Timeouts β Socket Timeout Using the Connection Manager
The only timeout that we can set when we configure the connection manager is the socket timeout:
Example 7.1. Setting Socket Timeout to 5 Seconds
final HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
final HttpContext context = new BasicHttpContext();
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
final ConnectionConfig connConfig = ConnectionConfig.custom()
.setSocketTimeout(5, TimeUnit.SECONDS)
.build();
connManager.setDefaultConnectionConfig(connConfig);
final LeaseRequest leaseRequest = connManager.lease("id1", route, null);
final ConnectionEndpoint endpoint = leaseRequest.get(Timeout.ZERO_MILLISECONDS);
connManager.connect(endpoint, null, context);
connManager.close();
For a more in-depth discussion of timeouts in the HttpClient, see here.
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
8. Connection Eviction
We use connection eviction to detect idle and expired connections and close them. We have two options to do this:
Example 8.1. Setting the HttpClient to Check and evict the Stale Connections
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
try (final CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.evictExpiredConnections()
.evictIdleConnections(TimeValue.ofSeconds(2))
.build()) {
// create an array of URIs to perform GETs on
final String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/"};
for (final String requestURI : urisToGet) {
final HttpGet request = new HttpGet(requestURI);
System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri());
httpclient.execute(request, response -> {
System.out.println("----------------------------------------");
System.out.println(request + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
final PoolStats stats1 = connManager.getTotalStats();
System.out.println("Connections kept alive: " + stats1.getAvailable());
// Sleep 4 sec and let the connection evict or do its job
Thread.sleep(4000);
final PoolStats stats2 = connManager.getTotalStats();
System.out.println("Connections kept alive: " + stats2.getAvailable());
}
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
9. Connection Closing
We can close a connection gracefully (we make an attempt to flush the output buffer prior to closing), or we can do it forcefully, by calling the shutdown method (the output buffer is not flushed).
To properly close connections, we need to do all of the following:
- Consume and close the response (if closeable)
- Close the client
- Close and shut down the connection manager
Example 9.1. Closing Connection and Releasing Resources
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
final HttpGet get = new HttpGet("http://google.com");
CloseableHttpResponse response = client.execute(get);
EntityUtils.consume(response.getEntity());
response.close();
client.close();
connManager.close();
If we shut down the manager without closing connections already, all connections will be closed and all resources released.
Itβs important to keep in mind that this will not flush any data that may have been ongoing for the existing connections.
For the relative Javadoc of version 4.5, check this link and the github link in the Conclusion section.
10. Conclusion
In this article, we discussed how to use the HTTP Connection Management API of HttpClient to handle the entire process of managing connections. This included opening and allocating them, managing their concurrent use by multiple agents and finally closing them.
We saw how the BasicHttpClientConnectionManager is a simple solution to handle single connections and how it can manage low-level connections.
We also saw how the PoolingHttpClientConnectionManager combined with the HttpClient API provide for an efficient and protocol-compliant use of HTTP connections.
