gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:29:26 26 4
gpt4 key购买 nike

正如标题所说,我想知道如何在 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

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

非常感谢您!

最佳答案

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

关于java - 如何使用 HTTPClient (Java 11) 的 HTTP 选项方法发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com