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 show how to enable logging in Apacheβs HttpClient. Additionally, weβll explain how logging is implemented inside the library. Afterward, weβll show how to enable different levels of logging.
2. Logging Implementation
The HttpClient library provides efficient, up-to-date, and feature-rich implementation client site of the HTTP protocol.
Indeed as a library, HttpClient doesnβt force logging implementation. With this intention, version 4.5, provides logs with Commons Logging. Similarly, the latest version, 5.1, uses a logging facade provided by SLF4J. Both versions use a hierarchy schema to match loggers with their configurations.
Thanks to that, it is possible to set up loggers for single classes or for all classes related to the same functionality.
3. Log Types
Letβs have a look at log levels defined by the library. We can distinguish 3 types of logs:
- context logging β logs information about all internal operations of HttpClient. It contains wire and header logs as well.
- wire logging β logs only data transmitted to and from the server
- header logging β logs HTTP headers only
In version 4.5 the corresponding packages are org.apache.http.impl.client and org.apache.http.wire, org.apache.http.headers.
Acordingly in version 5.1 the are packages org.apache.hc.client5.http, org.apache.hc.client5.http.wire and org.apache.hc.client5.http.headers.
4. Log4j Configuration
Letβs have a look at how to enable logging in to both versions. Our aim is to achieve the same flexibility in both versions. In version 4.1, weβll redirect logs to SLF4j. Thanks to that, different logging frameworks can be used.
4.1. Version 4.5 Configuration
Letβs add the httpclient dependency:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
Weβll use jcl-over-slf4j to redirect logs to SLF4J. Therefore we excluded commons-logging. Letβs then add a dependency to the bridge between JCL and SLF4J:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.32</version>
</dependency>
Because SLF4J is just a facade, we need a binding. In our example, weβll use logback:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.6</version>
</dependency>
Letβs now create the ApacheHttpClientUnitTest class:
public class ApacheHttpClientUnitTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
HttpGet request = new HttpGet(DUMMY_URL);
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
logger.debug("Response -> {}", EntityUtils.toString(entity));
}
}
}
The test fetches a dummy web page and prints the contents to the log.
Letβs now define a logger configuration with our logback.xml file:
<configuration debug="false">
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date [%level] %logger - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.baeldung.httpclient.readresponsebodystring" level="debug"/>
<logger name="org.apache.http" level="debug"/>
<root level="WARN">
<appender-ref ref="stdout"/>
</root>
</configuration>
After running our test, all HttpClientβs logs can be found in the console:
...
2021-06-19 22:24:45,378 [DEBUG] org.apache.http.impl.execchain.MainClientExec - Executing request GET /get HTTP/1.1
2021-06-19 22:24:45,378 [DEBUG] org.apache.http.impl.execchain.MainClientExec - Target auth state: UNCHALLENGED
2021-06-19 22:24:45,379 [DEBUG] org.apache.http.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
2021-06-19 22:24:45,382 [DEBUG] org.apache.http.headers - http-outgoing-0 >> GET /get HTTP/1.1
...
4.2. Version 5.1 Configuration
Letβs have a look now at the higher version. It contains redesigned logging. Therefore, instead of Commons Logging, it utilizes SLF4J. As a result, a binding for the logger facade is the only additional dependency. Therefore weβll use logback-classic as in the first example.
Letβs add the httpclient5 dependency:
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1</version>
</dependency>
Letβs add a similar test as in the previous example:
public class ApacheHttpClient5UnitTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseApacheHttpClient_thenCorrect() throws IOException, ParseException {
HttpGet request = new HttpGet(DUMMY_URL);
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
logger.debug("Response -> {}", EntityUtils.toString(entity));
}
}
}
Next, we need to add a logger to the logback.xml file:
<configuration debug="false">
...
<logger name="org.apache.hc.client5.http" level="debug"/>
...
</configuration>
Letβs run the test class ApacheHttpClient5UnitTest and check the output. It is similar to the old version:
...
2021-06-19 22:27:16,944 [DEBUG] org.apache.hc.client5.http.impl.classic.InternalHttpClient - ep-0000000000 endpoint connected
2021-06-19 22:27:16,944 [DEBUG] org.apache.hc.client5.http.impl.classic.MainClientExec - ex-0000000001 executing GET /get HTTP/1.1
2021-06-19 22:27:16,944 [DEBUG] org.apache.hc.client5.http.impl.classic.InternalHttpClient - ep-0000000000 start execution ex-0000000001
2021-06-19 22:27:16,944 [DEBUG] org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager - ep-0000000000 executing exchange ex-0000000001 over http-outgoing-0
2021-06-19 22:27:16,960 [DEBUG] org.apache.hc.client5.http.headers - http-outgoing-0 >> GET /get HTTP/1.1
...
5. Conclusion
That concludes this short tutorial on how to configure logging for Apacheβs HttpClient. Firstly, we explained how logging is implemented in the library. Secondly, we configured logging in two versions and executed simple test cases to show the output.
