Sub topic 5
Sending a Request with `send`
Assume you understand Java 11 or later, HTTP methods and status codes, and checked exceptions. This chapter uses a reusable HttpClient, an HttpRequest, and a response body handler.
How `send` works
HttpClient.send performs a synchronous HTTP request. Synchronous means the current thread waits until the server returns a response or the request fails. The method returns an HttpResponse<T>, where T is the type produced by the body handler.
The request flow is:
A body handler tells Java how to consume the response body. BodyHandlers.ofString() creates a String, which is useful for text and JSON responses.
A complete GET request
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class SimpleGet {
public static void main(String[] args)
throws java.io.IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.header("Accept", "text/html")
.timeout(Duration.ofSeconds(10))
.GET()
.build();
HttpResponse<String> response = client.send(
request,
HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println(response.body());
}
}send can throw IOException when communication fails and InterruptedException when the waiting thread is interrupted. The example declares both exceptions in main. Production code often catches them so it can log the failure or return an application-specific error.
The status code is part of the response, not an exception. A server can return 404 Not Found or 500 Internal Server Error, and send still returns normally. Your code must inspect response.statusCode().
Choosing the response body
The body handler controls memory use and the response type.
| Handler | Response body type | Typical use |
|---|---|---|
| `ofString()` | `String` | Small text or JSON |
| `ofByteArray()` | `byte[]` | Small binary content |
| `ofFile(path)` | `Path` | Large downloads |
| `ofLines()` | `Stream<String>` | Line-oriented text |
Exercise
Does send throw an exception automatically for an HTTP 404 response?
Show answer
No. It returns an HttpResponse; inspect the status code and handle non-2xx responses yourself.