HttpResponse
The server response: the status code, headers and a body of the type chosen by the BodyHandler.
Available since: Java 11
Syntax
public interface HttpResponse<T>Examples
The code, a header and the body. A 404 response does not throw:
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
void main() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", exchange -> {
byte[] body = "{\"error\": \"not found\"}".getBytes();
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(404, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/missing");
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString());
IO.println(response.statusCode());
IO.println(response.headers().firstValue("Content-Type").orElse("none"));
IO.println(response.body());
if (response.statusCode() >= 400) {
IO.println("Request failed");
}
}
server.stop(0);
}Output:
404
application/json
{"error": "not found"}
Request failedBodyHandlers.ofLines() gives the body as a stream of lines:
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
void main() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/log", exchange -> {
byte[] body = "INFO start\nERROR disk full\nINFO stop".getBytes();
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/log");
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<Stream<String>> response = client.send(
HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofLines());
response.body().filter(line -> line.startsWith("ERROR")).forEach(IO::println);
}
server.stop(0);
}Output:
ERROR disk fullNotes
The body type is set by a handler from BodyHandlers: ofString() gives a string, ofLines() a stream of lines, ofByteArray() bytes, ofFile(path) writes straight to a file, discarding() when the body is not needed. 4xx and 5xx codes do not throw, so always check statusCode(). Headers are read with headers().firstValue(name), which returns an Optional. To turn JSON into an object use a separate library such as Jackson.
See also
- HttpClient — The built-in HTTP client: sends requests synchronously (send) or asynchronously (sendAsync).
- HttpRequest — An immutable HTTP request: address, method, headers and body. Created with newBuilder().
- Optional — A container that either holds a value or is empty — a replacement for returning `null`.
In the tutorial
- HTTP client — Making requests to web servers from Java — HttpClient, HttpRequest and HttpResponse.BodyHandlers, GET and POST with JSON, status codes and asynchronous sendAsync.