如何通过 HTTPClient (Java 11) 使用 HTTP 选项方法发送请求?

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

正如标题所说,我想知道如何在Java中使用带有 OPTIONS 方法的 HTTPClient 发送 HTTP 请求。我查看了可以使用的 HTTP 方法(GET、POST、PUT 和 DELETE),但没有看到此选项。 使用 HTTPClient 的 GET/POST 请求示例如下:

String uri = "https://www.whosebug.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

如果无法使用(这对我来说似乎非常罕见),我可以使用什么替代方案?

非常感谢您!

HttpRequest.Builder 有一个 .method​(String method, HttpRequest.BodyPublisher bodyPublisher) 方法,它允许您设置与定义的快捷方式不同的 HTTP 方法,例如 .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()

正如所说 HttpRequest.Builder 有一个 .method​(String method, HttpRequest.BodyPublisher bodyPublisher) 让你配置你的方法。

这是OPTIONS方法的示例

HttpRequest request = HttpRequest.newBuilder()
                                 .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
                                 .uri(URI.create("http://localhost/api"))
                                 .build();