如何使用Java中的新HTTP客户端在POST()请求中传递参数



我刚开始在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&param2=value2&param3=value3&param4=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());

最新更新