How can I send a request using the HTTP Options method with HTTPClient (Java 11)?

PablooD9 :

As the title says, I would like to know how to send an HTTP request using HTTPClient with the OPTIONS method in Java. I have looked at the HTTP methods that can be used (GET, POST, PUT and DELETE) and I have not seen this option. An example of a GET/POST request with HTTPClient would be like this:

String uri = "https://www.stackoverflow.com/"
HttpRequest.Builder preRequest=null;

// EXAMPLE OF GET REQUEST
preRequest = HttpRequest.newBuilder()
.uri(URI.create( uri ))
.GET();

// EXAMPLE OF POST REQUEST
preRequest = HttpRequest.newBuilder()
.uri(URI.create( uri ))
.POST(BodyPublishers.ofString(req.getBody()));  // "req" is an object of a class made by me, it does not matter in this context

In case it can't be used (which would seem extremely rare to me), what alternative can I use?

Thank you very much in advance!

Elias :

HttpRequest.Builder has a .method​(String method, HttpRequest.BodyPublisher bodyPublisher) method which allows you to set a different HTTP method than the defined shortcuts such as .POST(HttpRequest.BodyPublisher bodyPublisher).

HttpRequest.Builder
method​(String method, HttpRequest.BodyPublisher bodyPublisher)

Sets the request method and request body of this builder to the given values.

https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.html#method()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140316&siteId=1