我刚开始在Java中使用新的HTTP客户端,我不确定如何为PUT请求传递参数。
我正在处理的特定请求需要一个Authentication
令牌和一个参数type
。
- 我已经使用
.headers()
成功处理了Authentication
令牌 - 我尝试对
type
参数执行同样的操作,但收到一条错误消息,指出我没有传递type
字段
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("...")) # The API url
.headers("Authorization", token, "type", "type 1")
.POST(HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
正如@ernest_k所评论的,我们可以通过将参数附加到URL的末尾来传递参数,格式如下:?type=type1¶m2=value2¶m3=value3¶m4=value4
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("..." + "?type=type 1"))
.headers("Authorization", token)
.POST(HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());