繁体   English   中英

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

[英]How to pass parameters in a POST() request using the new HTTP client in Java

我刚开始在 Java 中使用新的 HTTP 客户端,我不确定如何为 PUT 请求传递参数。

我正在处理的特定请求需要一个Authentication token 和一个参数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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM