HttpClient Sync GET Status And Headers

Send a blocking HTTP request with HttpClient.send and inspect status code, headers, and body length, the sync counterpart to the async chaining API.

JavaData Fetching

Code

snippet
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SyncStatusCheck {

    public static void main(String[] args) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://example.com/"))
                .header("Accept", "text/html")
                .GET()
                .build();

        // send() is the synchronous (blocking) call: it returns only with the response; see sendAsync for the chaining counterpart
        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("n/a"));
        System.out.println("body chars: " + response.body().length());
    }
}

How it works

HttpClient Sync GET Status And Headers is built around the class SyncStatusCheck.

Caveats

  • No external surface: all behavior comes from the standard library.

Putting it to use

Running the file prints labeled results such as status:, content-type:, body chars: — each operation’s effect is visible in the output.

Core lines

client.send(request, HttpResponse.BodyHandlers.ofString());
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.header("Accept", "text/html")
.GET()
.build();

Interactive Tools for This Topic

FAQ

What does HttpClient Sync GET Status And Headers print when run?
Invoke the file as-is — the `status:`, `content-type:`, `body chars:` prefixes identify which step printed each line.