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

时间:2021-05-11 08:18:09

标签: java rest http

我刚开始在 Java 中使用 new HTTP client,但不确定如何为 PUT 请求传递参数。

我正在处理的特定请求需要一个 Authentication 令牌和一个参数 type

  • 我已经使用 Authentication 成功处理了 .headers() 令牌
  • 我尝试对 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());

1 个答案:

答案 0 :(得分:0)

正如@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());