How do I handle GZIP or compressed responses with Java 11 HttpClient?

Handling GZIP or compressed responses using the Java 11 HttpClient is straightforward. The HttpClient automatically supports GZIP compression, but you need to specify the Accept-Encoding header in the request to indicate that you accept compressed responses, and it will handle decompression automatically if the server responds with compressed data.

Here’s how you can do it:

Example Code

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GzipResponseExample {
   public static void main(String[] args) {
      try {
         // Create an HttpClient
         HttpClient httpClient = HttpClient.newHttpClient();

         // Build the HTTP request
         HttpRequest request = HttpRequest.newBuilder()
                 .uri(URI.create("https://example.com"))
                 .header("Accept-Encoding", "gzip") // Indicate support for GZIP responses
                 .build();

         // Send the HTTP request and expect a response
         HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

         // Print the response body
         System.out.println("Response code: " + response.statusCode());
         System.out.println("Response body: " + response.body());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Explanation

  1. HttpClient Creation:
    • An HttpClient instance is created using HttpClient.newHttpClient(), which is reusable.
  2. Request Building:
    • Specify the header Accept-Encoding: gzip to indicate that your client can handle GZIP-compressed responses from the server.
  3. Send Request:
    • The .send() method sends the HTTP request and receives the response. The BodyHandlers.ofString() body handler is used to handle the response body as a decompressed String.
  4. Server-Side Behavior:
    • If the server supports GZIP compression, it might send a response with the header Content-Encoding: gzip.
    • The HttpClient automatically detects and decompresses the GZIP response for you.

Notes:

  • You don’t need to manually handle decompression when using HttpClient. It takes care of the compression and decompression process internally.
  • If the server does not compress the response, the HttpClient simply returns the regular response.

Debugging:

To verify whether the response was compressed:

  • Check the Content-Encoding header in the response. It will show "gzip" if the server sent a compressed response.

Example to log headers:

System.out.println("Headers: " + response.headers());

This approach adheres to modern standards and makes working with compressed HTTP responses simple and efficient in Java!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.