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.
Code
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
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.HTTP Header AnalyzerPaste raw HTTP header lines and get a parsed name-value list with plain-language notes for common headers and security observations.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.