1. Introduction
When working with HTTP clients in Java, especially during development and debugging, it's incredibly helpful to log requests and responses. OkHttp provides a convenient way to achieve this using interceptors, specifically the HttpLoggingInterceptor
.
2. Dependency Setup
If you haven't already added OkHttp to your project, you can do so via Maven or Gradle.
✅ Maven:
xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
✅ Gradle:
groovy
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
3. Logging with HttpLoggingInterceptor
OkHttp’s HttpLoggingInterceptor
makes it easy to log all parts of HTTP communication — from request headers to response bodies.
4. Java Code Example
java
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import java.io.IOException;
public class OkHttpLoggingExample {
public static void main(String[] args) {
// Step 1: Create a logging interceptor
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // Adjust the level as needed
// Step 2: Build OkHttpClient with the logging interceptor
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
// Step 3: Create a request
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
// Step 4: Execute the request
try {
Response response = client.newCall(request).execute();
// Optional: Print response manually
System.out.println("Response Body: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. Logging Levels
You can control how much information is logged with HttpLoggingInterceptor.Level
:
LevelDescriptionBODY
Logs request and response lines, headers, and full bodies (if present).HEADERS
Logs just the headers of request and response.BASIC
Logs request and response lines only.NONE
Disables all logging.
6. Sample Console Output (BODY Level)
bash
--> GET https://api.example.com/data
Content-Type: application/json
...
<-- 200 OK https://api.example.com/data (153ms)
Content-Type: application/json
Response Body: {"status":"ok","data":[...]}
7. Use Cases
- ✅ API debugging
- ✅ Verifying HTTP headers and payloads
- ✅ Monitoring production traffic (use lower log level)
- ✅ Logging API call performance (timing info)
8. Notes
- ⚠️ Avoid logging sensitive information like passwords or tokens in production environments.
- 🔒 Use
Level.HEADERS
or Level.BASIC
in production for minimal info. - 🧪 Ideal for debugging REST API interactions and tracing HTTP issues.