Home > Software > How to Read an HTTP Response Body as a String in Java

How to Read an HTTP Response Body as a String in Java

Anastasios Antoniadis

Share on X (Twitter) Share on Facebook Share on Pinterest Share on LinkedInWhen it comes to Java development, especially in web and network programming, handling HTTP requests and responses is a common task. One of the crucial aspects of dealing with HTTP responses is efficiently reading the response body. This is often required as a …

Java

When it comes to Java development, especially in web and network programming, handling HTTP requests and responses is a common task. One of the crucial aspects of dealing with HTTP responses is efficiently reading the response body. This is often required as a string for further processing, logging, or display purposes. In this article, we will guide you through the process of reading an HTTP response body as a string in Java. We will cover traditional approaches, as well as the modern approach introduced in Java 11.

Using HttpURLConnection

Before Java 11, HttpURLConnection was the go-to class for making HTTP requests and reading responses. It’s part of the java.net package and provides a base for web communication.

Steps to Read HTTP Response Body:

  1. Create a URL Object: Instantiate a URL object with the target HTTP endpoint.
  2. Open Connection: Call the openConnection() method on the URL object to obtain a HttpURLConnection instance.
  3. Set Request Method: Optionally set the request method (GET, POST, etc.) using setRequestMethod(String method).
  4. Read Response: Use an InputStreamReader and BufferedReader to read the response body from the connection’s input stream.

Example Code:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class HttpUrlConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.com");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");

        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            System.out.println(response.toString());
        } finally {
            con.disconnect();
        }
    }
}

This method is straightforward and works well for simple use cases. However, managing connections, handling exceptions, and ensuring resources are properly closed can add boilerplate code and complexity, especially for more advanced scenarios or when dealing with HTTPS.

Using HttpClient in Java 11+

Java 11 introduced the HttpClient class as part of the java.net.http package, offering a more modern and convenient way to handle HTTP requests and responses. It supports both synchronous and asynchronous operations and is designed to replace HttpURLConnection for new projects.

Steps to Read HTTP Response Body:

  1. Create an HttpClient: Use HttpClient.newHttpClient() or build one with specific configurations using HttpClient.newBuilder().
  2. Create an HttpRequest: Build an HttpRequest object with the request URI and other parameters like headers and request method.
  3. Send the Request and Get the Response: Use the send method of HttpClient for synchronous operations, specifying the HttpRequest and a BodyHandler to process the response body.

Example Code:

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

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://example.com"))
                .build();

        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

        System.out.println(response.body());
    }
}

This approach is more concise and reduces the boilerplate code significantly. The HttpClient class also handles much of the complexity associated with connection management, making it a superior choice for new projects.

Conclusion

Reading an HTTP response body as a string in Java can be achieved using either HttpURLConnection for applications targeting older Java versions or HttpClient for those leveraging Java 11 and newer. While HttpURLConnection still serves its purpose for simple HTTP requests, HttpClient offers a modern, versatile, and more efficient API for making HTTP requests and processing responses in Java. The choice between these two approaches depends on the specific requirements of your project and the Java version you are using.

Anastasios Antoniadis
Follow me
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x