I want to use Java 11 HttpClient and send header first, check response and if response is OK then send the body.
How can I send header only?
this is my current code:
HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .followRedirects(HttpClient.Redirect.NORMAL) .connectTimeout(Duration.ofSeconds(10)) .authenticator(Authenticator.getDefault()) .build(); HttpRequest httpRequest = HttpRequest.newBuilder("someEndpoint) .header(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(AUTHORIZATION, "someApiKey) .build(); HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
However with such httpResponse I understand I send the body.
Advertisement
Answer
By default, the header comes first in requests.
What you asked is, The first request with header and then with a body are two different requests. A single request can’t be broken this way.
If you are talking about, Http HEAD method usage, then The HEAD method asks for a response identical to that of a GET request, but without the response body.
The HTTP HEAD method requests the headers that would be returned if the HEAD request’s URL was instead requested with the HTTP GET method. For example, if a URL might produce a large download, a HEAD request could read its Content-Length header to check the file size without actually downloading the file.
an example to use HEAD method:-
var httpClient: HttpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build(); var requestHead = HttpRequest.newBuilder() .method("HEAD", HttpRequest.BodyPublishers.noBody()) .uri(URI.create("https://www.test.com")) .build(); val httpResponse = httpClient.send(requestHead, BodyHandlers.discarding()); HttpHeaders headers = response.headers(); headers.map().forEach((key, values) -> { System.out.printf("%s: %s%n", key, values); });