4

正如标题所说,我想知道如何使用 HTTPClient 和 Java 中的 OPTIONS 方法发送 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

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

非常感谢您!

4

2 回答 2

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()

于 2019-09-06T14:03:38.400 回答
0

As said HttpRequest.Builder has a .method​(String method, HttpRequest.BodyPublisher bodyPublisher) that let you configure your method.

This is an example for OPTIONS method

HttpRequest request = HttpRequest.newBuilder()
                                 .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
                                 .uri(URI.create("http://localhost/api"))
                                 .build();
于 2020-09-14T14:58:43.233 回答