When working with network requests, it's essential to log the details of both requests and responses to diagnose issues and ensure smooth communication with APIs. OkHttp, a popular HTTP client for Android and Java, provides powerful mechanisms for logging HTTP request and response data.
In this article, we'll explore how to log HTTP request and response details using OkHttp through custom interceptors and built-in logging functionality.
Approach
Using Custom Logging Interceptor
OkHttp allows the use of interceptors, which can be used to inspect and log HTTP requests and responses. We can create a custom interceptor to log various request and response details like URL, headers, body content, and the time it takes for a response.
Step-by-Step Process
- Create a Custom Logging Interceptor
- The custom interceptor will intercept the request and response chain, log the relevant details, and allow the request to proceed.
- Add the Interceptor to OkHttpClient
- The logging interceptor is added to the OkHttpClient instance, allowing it to log requests and responses for every HTTP call.
- Make a Request Using OkHttpClient
- Once the OkHttpClient is set up with the logging interceptor, make requests using the client. The interceptor will log the details automatically.
Java Code Implementation
1. Create a Custom Logging Interceptor
Here is the implementation of a custom logging interceptor that logs request and response details:
java
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.IOException;
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Log request details
long t1 = System.nanoTime();
System.out.println(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
// Log response details
long t2 = System.nanoTime();
System.out.println(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
// If you want to log the response body
ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
System.out.println("Response Body: " + responseBody.string());
return response;
}
}
2. Adding the Interceptor to OkHttpClient
You can now add the custom logging interceptor to the OkHttpClient
instance:
java
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
3. Making a Request
Now, you can make requests using the OkHttpClient
instance. The interceptor will log the request and response details automatically:
java
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// Example URL
String url = "https://api.example.com/endpoint";
// Create request
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Print response body
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. Using OkHttp’s Built-In Logging
OkHttp also provides a built-in logging interceptor called HttpLoggingInterceptor
. This is an easy-to-use alternative if you don’t need to create a custom interceptor.
java
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.OkHttpClient;
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
5. Log Levels with HttpLoggingInterceptor
You can adjust the verbosity of the logs by setting the log level. The available levels are:
- NONE: No logging.
- BASIC: Logs request and response lines.
- HEADERS: Logs request and response lines and their respective headers.
- BODY: Logs request and response lines, headers, and bodies (if present).
Example of setting the logging level to BODY
:
java
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
Example Output:
When making a request, you will see logs like the following in your console:
bash
Sending request https://api.example.com/endpoint on okhttp3.OkHttpClient$1@e1b47f8
Request Headers: {Accept=[application/json], User-Agent=[okhttp/4.9.0]}
Received response for https://api.example.com/endpoint in 150.1ms
Response Headers: {Content-Type=[application/json; charset=utf-8], Cache-Control=[no-cache]}
Response Body: {"status":"success","data":[...]}
Conclusion
Logging requests and responses is essential for debugging network-related issues and ensuring smooth communication with APIs. With OkHttp, you can easily log HTTP request and response details using custom interceptors or the built-in HttpLoggingInterceptor
.
You can customize the level of detail in the logs to fit your needs, making it a powerful tool for monitoring API interactions.