How to log request/response using java.net.http.HttpClient?
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
If we look at jdk.internal.net.http.common.DebugLogger
source code we can see a few loggers using System.Logger
, which in turn will useSystem.LoggerFinder
to select the logger framework. JUL is the default choice. The logger names are:
- jdk.internal.httpclient.debug
- jdk.internal.httpclient.websocket.debug
- jdk.internal.httpclient.hpack.debug
They can be enabled by setting them as a system property. For example running with -Djdk.internal.httpclient.debug=true
will produce:
DEBUG: [main] [147ms] HttpClientImpl(1) proxySelector is sun.net.spi.DefaultProxySelector@6dde5c8c (user-supplied=false)
DEBUG: [main] [183ms] HttpClientImpl(1) ClientImpl (async) send https://http2.github.io/ GET
DEBUG: [main] [189ms] Exchange establishing exchange for https://http2.github.io/ GET,
proxy=null
DEBUG: [main] [227ms] PlainHttpConnection(?) Initial receive buffer size is: 43690
DEBUG: [main] [237ms] PlainHttpConnection(SocketTube(1)) registering connect event
DEBUG: [HttpClient-1-SelectorManager] [239ms] SelectorAttachment Registering jdk.internal.net.http.PlainHttpConnection$ConnectEvent@354bf356 for 8 (true)
...