Debugging HTTP can be very tricky. You have methods, headers, cookies, sessions, ssl, redirects, status codes and many other considerations. Making sure you set up proper logging for debugging purposes will allow you to track down issues much faster. The number one debugging tool for any HTTP client should without question be cURL. Once you are comfortable with cURL you can have absolute confidence you know a request should be working. Now you just need to track down the differences from cURL and your Java HTTP client of choice. Let's take a look at logging with OkHttp.

OkHttp Interceptors

Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls. Basically interceptors are equivalent to our Undertow Middleware. An interceptor is the perfect place for request / response logging in OkHttp. They even provide an excellent HttpLoggingInterceptor as an extra library. Simply set the level you want and provide your own logging mechanism to log the provided messages. We will be using SLF4J with Logback to create a static singleton HttpLoggingInterceptor.

private static final Logger log = LoggerFactory.getLogger(HttpClient.class);

private static final HttpLoggingInterceptor loggingInterceptor =
    new HttpLoggingInterceptor((msg) -> {
        log.debug(msg);
    });
static {
    loggingInterceptor.setLevel(Level.BODY);
}

public static HttpLoggingInterceptor getLoggingInterceptor() {
    return loggingInterceptor;
}

The HttpLoggingInterceptor.setLevel has a few modes. Level.NONE - no logs, Level.BASIC - Logs request and response lines, Level.HEADERS - Logs request and response lines and their respective headers, and Level.BODY - Logs request and response lines and their respective headers and bodies (if present). Use Level.BODY with caution, running it in production may unintentionally log passwords or secrets to your log files since it dumps the full request / response body.

OkHttp Interceptor Types

OkHttp has two types of interceptors that both use the exact same interface. Application interceptors are higher level and tend to deal with the final request / response. Application interceptors are great for high level logging or adding headers / query parameters to every HTTP request. Network interceptors operate at a lower level and follow all network bounces / redirects as well as caching. Network interceptors are much more in depth and a great spot for detailed logging. For more information on interceptors check out the official wiki

Example Routes

To show differences between application interceptors and network interceptors types let's add a route that redirects to an another route.

private static final HttpHandler ROUTES = new RoutingHandler()
    .get("/ping", timed("ping", (exchange) -> Exchange.body().sendText(exchange, "ok")))
    .get("/redirectToPing", (exchange) -> Exchange.redirect().temporary(exchange, "/ping"))
    .setFallbackHandler(timed("notFound", RoutingHandlers::notFoundHandler))
;

Request Helper

Simple helper method for sending the HTTP request with a given OkHttpClient

private static void request(OkHttpClient client, String url) {
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    Unchecked.supplier(() -> {
        Response response = client.newCall(request).execute();
        log.debug("{} - {}", response.code(), response.body().string());
        return null;
    }).get();
}

OkHttp Without A Logging Interceptor

We are not using any logging interceptors here so we should expect no logging info.

log.debug("noLogging");
OkHttpClient client = new OkHttpClient.Builder().build();
request(client, "http://localhost:8080/redirectToPing");
2017-03-08 14:18:39.984 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - noLogging
2017-03-08 14:18:40.354 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - 200 - ok

OkHttp With an Application Logging Interceptor

Here we are passing in the logging interceptor at the higher level application interceptor.

log.debug("interceptor");
OkHttpClient interceptorClient = new OkHttpClient.Builder()
    .addInterceptor(HttpClient.getLoggingInterceptor())
    .build();
request(interceptorClient, "http://localhost:8080/redirectToPing");
2017-03-08 14:18:40.356 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - interceptor
2017-03-08 14:18:40.367 [main] DEBUG com.stubbornjava.common.HttpClient - --> GET http://localhost:8080/redirectToPing http/1.1
2017-03-08 14:18:40.367 [main] DEBUG com.stubbornjava.common.HttpClient - --> END GET
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - <-- 200 OK http://localhost:8080/ping (3ms)
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: keep-alive
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Type: text/plain
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Length: 2
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - Date: Wed, 08 Mar 2017 19:18:40 GMT
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - 
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - ok
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - <-- END HTTP (2-byte body)
2017-03-08 14:18:40.372 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - 200 - ok

Notice how we were redirected as expected but there is no indication any redirecting occured.

OkHttp With A Network Logging Interceptor

Here we are passing in the logging interceptor at the lower level network interceptor.

log.debug("networkInterceptor");
OkHttpClient networkInterceptorClient = new OkHttpClient.Builder()
    .addNetworkInterceptor(HttpClient.getLoggingInterceptor())
    .build();
request(networkInterceptorClient, "http://localhost:8080/redirectToPing");
2017-03-08 14:18:40.373 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - networkInterceptor
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - --> GET http://localhost:8080/redirectToPing http/1.1
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - Host: localhost:8080
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: Keep-Alive
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - Accept-Encoding: gzip
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - User-Agent: okhttp/3.6.0
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - --> END GET
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - <-- 302 Found http://localhost:8080/redirectToPing (1ms)
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: keep-alive
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Location: /ping
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Length: 0
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Date: Wed, 08 Mar 2017 19:18:40 GMT
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - <-- END HTTP (0-byte body)
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - --> GET http://localhost:8080/ping http/1.1
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - Host: localhost:8080
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: Keep-Alive
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - Accept-Encoding: gzip
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - User-Agent: okhttp/3.6.0
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - --> END GET
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - <-- 200 OK http://localhost:8080/ping (1ms)
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: keep-alive
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Type: text/plain
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Length: 2
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Date: Wed, 08 Mar 2017 19:18:40 GMT
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - 
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - ok
2017-03-08 14:18:40.383 [main] DEBUG com.stubbornjava.common.HttpClient - <-- END HTTP (2-byte body)
2017-03-08 14:18:40.383 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - 200 - ok

Notice how we were redirected as expected and the log clearly shows all the network hops.