Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log request/response using java.net.http.HttpClient?

Tags:

The HttpClient introduced experimentally in Java 9 is now stable in Java 11, but not surprisingly, very few projects seem to actually use it. Documentation is almost non-existing.

One of the most commons asks while making a HTTP call is logging of request/response. How would you do that using the HttpClient, without of course, logging it manually in every single call? Is there an interceptor mechanism like that offered by all other HTTP clients?

like image 510
Abhijit Sarkar Avatar asked Nov 08 '18 19:11

Abhijit Sarkar


People also ask

How do you read a response body in Java?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

Is Java net http HttpClient thread safe?

Once created, an HttpClient instance is immutable, thus automatically thread-safe, and you can send multiple requests with it.

Does Apache HttpClient use Log4j?

Note: Log4j is not included in the HttpClient distribution.


1 Answers

You can log request and responses by specifying -Djdk.httpclient.HttpClient.log=requests on the Java command line.

As for testing/mocking you might want to have a look at the offline test: http://hg.openjdk.java.net/jdk/jdk/file/tip/test/jdk/java/net/httpclient/offline/

Depending on what you are looking to achieve you could use a "DelegatingHttpClient" to intercept and log requests and responses too.

Besides the Java API documentation there's also some high level documentation at http://openjdk.java.net/groups/net/httpclient/index.html

Additional note:

The jdk.httpclient.HttpClient.log property is an implementation specific property whose value is a comma separated list which can be configured on the Java command line for diagnosis/debugging purposes with the following values:

-Djdk.httpclient.HttpClient.log=        errors,requests,headers,        frames[:control:data:window:all],content,ssl,trace,channel,all 
like image 149
daniel Avatar answered Oct 16 '22 19:10

daniel