How do I fetch JSON using java.net.http.HttpRequest?

To fetch JSON using the Java HTTP Client (java.net.http), you typically send a GET request and process the response body as a String. Since the standard library doesn’t include a JSON parser, you’ll receive the raw JSON string, which you can then parse using a library like Jackson or Gson.

Here is a clean example of how to perform the fetch:

1. Basic JSON Fetch (Java 11+)

This example demonstrates the core steps: creating the client, building the request, and receiving the response.

package org.kodejava.httpclient;

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

public class FetchJsonExample {
    public static void main(String[] args) {
        // 1. Create an HttpClient (try-with-resources available in Java 21+)
        try (HttpClient client = HttpClient.newHttpClient()) {

            // 2. Build the HttpRequest
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                    .header("Accept", "application/json") // Good practice to request JSON
                    .GET()
                    .build();

            try {
                // 3. Send the request and handle the body as a String
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

                // 4. Check the status code and print the JSON body
                if (response.statusCode() == 200) {
                    System.out.println("JSON Received:");
                    System.out.println(response.body());
                } else {
                    System.err.println("Error: " + response.statusCode());
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2. Fetching Asynchronously

If you don’t want to block the main thread while waiting for the network, use sendAsync. This returns a CompletableFuture:

client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join(); // Wait for completion (for demo purposes)

Key Tips for JSON fetching:

  • Headers: Always include .header("Accept", "application/json") so the server knows you expect a JSON response.
  • Parsing: To turn that String into a Java Object, you would typically use a library. For example, with Jackson:
    ObjectMapper mapper = new ObjectMapper();
        MyObject obj = mapper.readValue(response.body(), MyObject.class);
    
  • Timeouts: It’s a “friendly” habit to set a timeout so your application doesn’t hang indefinitely:
    HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(java.time.Duration.ofSeconds(10))
                .build();
    

Leave a Reply

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