Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make an HTTP request

Short answer

The built-in HttpClient (Java 11) sends requests without third-party libraries. The example uses the network, so the result depends on the server:

void main() throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/")).GET().build();
 
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
 
    IO.println(response.statusCode());
    IO.println(response.body().length());
}

The program prints the status code (for example, 200) and the length of the received page.

POST with JSON

The request body goes through BodyPublishers, headers through header():

void main() throws Exception {
    String json = """
            {"name": "Anna", "email": "anna@site.com"}
            """;
    HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/users"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();
 
    HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
    IO.println(response.statusCode());
}

Timeouts

Set a connect timeout on the client and a response timeout on the request:

void main() throws Exception {
    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
            .timeout(Duration.ofSeconds(10))
            .build();
 
    try {
        IO.println(client.send(request, HttpResponse.BodyHandlers.ofString()).statusCode());
    } catch (HttpTimeoutException e) {
        IO.println("Server did not answer in time");
    }
}

Common mistake

Assuming a 404 or 500 response is an exception. HttpClient throws only on network errors, and server error codes arrive as a normal response. Always check response.statusCode(). Parse a JSON response with a library — Jackson or Gson.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.