Programming & Development / April 19, 2025

How to Extract JSON Body from an OkHttp Request Object

OkHttp RequestBody JSON extraction request logging buffer content type Java HTTP client API debugging

When working with APIs using OkHttp, you may encounter situations where you need to inspect the JSON payload being sent in a request—especially during development, debugging, or testing. Fortunately, OkHttp provides the tools to access and read the request body before it's sent to the server.

In this article, we’ll explore how to extract the JSON body from an OkHttp Request object in Java.

Use Case

You may need to:

  • Log the full JSON payload being sent in a request.
  • Debug unexpected request payload issues.
  • Perform conditional processing based on request content in an interceptor.

Approach

To extract the JSON body from an OkHttp Request object:

  1. Retrieve the RequestBody.
  2. Verify its content type is application/json.
  3. Use Okio’s Buffer to read the body content into a string.

Java Code Implementation

1. Extracting JSON from RequestBody

java

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;
import java.io.IOException;

public class RequestBodyExtractor {

    public static String extractJsonFromRequest(Request request) {
        RequestBody requestBody = request.body();

        if (requestBody != null && requestBody.contentType() != null) {
            MediaType contentType = requestBody.contentType();

            // Check if the request body is JSON
            if ("json".equals(contentType.subtype())) {
                try {
                    Buffer buffer = new Buffer();
                    requestBody.writeTo(buffer);         // Write the body to a buffer
                    return buffer.readUtf8();            // Read it as a UTF-8 string
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null; // Return null if there's no JSON body
    }

    public static void main(String[] args) {
        // Sample request with JSON body
        Request request = new Request.Builder()
            .url("https://api.example.com/endpoint")
            .post(RequestBody.create("{\"key\":\"value\"}", MediaType.get("application/json; charset=utf-8")))
            .build();

        // Extract and print the JSON body
        String jsonBody = extractJsonFromRequest(request);
        if (jsonBody != null) {
            System.out.println("JSON Body: " + jsonBody);
        } else {
            System.out.println("No JSON body found.");
        }
    }
}

Explanation

  • Request Body Retrieval:
  • We use request.body() to get the RequestBody from the Request object.
  • Content-Type Check:
  • Using requestBody.contentType(), we ensure the body is of type application/json to avoid reading incompatible formats.
  • Using Buffer:
  • A Buffer from Okio temporarily holds the body’s data. We write the request body into it and read the UTF-8 string.
  • Safe Fallback:
  • If the request body is not present or not JSON, the method returns null.

Use in Interceptors

This method is especially useful inside custom interceptors if you want to inspect or log request bodies conditionally:

java

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String json = RequestBodyExtractor.extractJsonFromRequest(request);
    System.out.println("Outgoing JSON Body: " + json);
    return chain.proceed(request);
}

Important Notes

  • One-Time Read:
  • RequestBody.writeTo() can only be safely called once. If you consume it in an interceptor, you may need to clone or rebuild the request.
  • Large Payloads:
  • Be cautious when printing large bodies; consider truncating or logging selectively.

Conclusion

Extracting the JSON payload from an OkHttp Request object can be incredibly useful for debugging and logging. With the help of Okio’s Buffer and a few checks, you can safely retrieve and print the raw JSON string. This utility method can be integrated into interceptors, test cases, or custom clients for enhanced visibility during development.


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