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

Pab*_*oD9 4 java http options http-method java-http-client

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

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
Run Code Online (Sandbox Code Playgroud)

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

非常感谢您提前!

小智 5

HttpRequest.Builder有一个.method?(String method, HttpRequest.BodyPublisher bodyPublisher)方法允许您设置与定义的快捷方式不同的 HTTP 方法,例如.POST(HttpRequest.BodyPublisher bodyPublisher).

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

将此构建器的请求方法和请求正文设置为给定值。

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