Sub topic 2
Sending a Request with `send`
Assume Java 11 or later, basic HTTP knowledge, and familiarity with checked exceptions. HttpClient.send performs a request synchronously: the current thread waits until a response or failure arrives.
Send a request and read the response
An HttpRequest contains the target URI, method, headers, and optional body. An HttpResponse contains the status code, response headers, and body.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
public class SimpleGet {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.header("Accept", "text/html")
.GET()
.build();
try {
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Content type: "
+ response.headers().firstValue("content-type").orElse("unknown"));
System.out.println(response.body());
} catch (HttpTimeoutException e) {
System.err.println("Request timed out: " + e.getMessage());
} catch (IOException e) {
System.err.println("Network or response error: " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Request interrupted");
}
}
}BodyHandlers.ofString() collects the response body as a String. Other handlers can write directly to a file or deliver lines as they arrive.
A status such as 404 or 500 does not throw an exception. Check the status explicitly. Usually, statuses from 200 through 299 indicate success.
Send a request body
A BodyPublisher supplies bytes for a request body. For example, this builds a JSON POST request:
HttpRequest post = HttpRequest.newBuilder(
URI.create("https://api.example.com/items"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"name\":\"widget\"}"))
.build();HttpClient does not parse JSON itself. Use a JSON library such as Jackson to map a response string to Java objects.
Exercise
Does HttpClient.send throw an exception for an HTTP 404 response?
Show answer
No. It returns an HttpResponse, so your code must inspect statusCode().