Programming & Development / April 19, 2025

How to Log Requests and Responses Using OkHttp in Java

OkHttp Java HTTP logging interceptor request log response log HttpLoggingInterceptor API debugging

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:

LevelDescriptionBODYLogs request and response lines, headers, and full bodies (if present).HEADERSLogs just the headers of request and response.BASICLogs request and response lines only.NONEDisables 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.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex