'How to execute "OPTIONS" HTTP method request in Java 11 HttpClient

I need to replace Apache http client with java httpClient.

I have a test with an apache client that works well:

HttpOptions httpOptions = new HttpOptions(uploadUrl);
try (CloseableHttpResponse responseOld = httpclient.execute(httpOptions)) {
    assertEquals(200, responseOld.getStatusLine().getStatusCode());
    assertEquals("POST,OPTIONS", responseOld.getFirstHeader("Access-Control-Allow-Methods").getValue());
}

But when I change it to java client, it doesn't work. I use this code:

HttpClient javaClient = HttpClient.newBuilder().sslContext(initUnsecuredSSLContext()).build();

HttpRequest get = HttpRequest.newBuilder()
                .uri(URI.create(uploadUrl))
                .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
                .build();
HttpResponse<String> response = javaClient.send(get, HttpResponse.BodyHandlers.ofString());

Test fails to complete when run

java version "17.0.2".

Thanks.



Solution 1:[1]

Everything was solved with a small change in response

HttpRequest get = HttpRequest.newBuilder()
                .uri(URI.create(uploadUrl))
                .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
                .build();

HttpResponse<Stream<String>> response = javaClient.send(get, HttpResponse.BodyHandlers.ofLines());

assertEquals(200, response.statusCode());
assertEquals("POST,OPTIONS", response.headers().firstValue("Access-Control-Allow-Methods").orElseThrow());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aleks Crow