Java 11:新HTTP客户端使用x-www-form-urlencoded参数发送POST请求

Java 11:新HTTP客户端使用x-www-form-urlencoded参数发送POST请求,java,java-http-client,Java,Java Http Client,我正在尝试使用新的http客户端api发送POST请求。 是否有一种内置方式来发送格式化为x-www-form-urlencoded的参数 我当前的代码: HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Content-Type", "application/x-www-form-urlencoded") .POST(BodyPublishe

我正在尝试使用新的http客户端api发送POST请求。 是否有一种内置方式来发送格式化为
x-www-form-urlencoded
的参数

我当前的代码:

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .POST(BodyPublishers.ofString("a=get_account&account=" + URLEncoder.encode(account, "UTF-8")))
        .build();
我在寻找传递参数的更好方法。大概是这样的:

Params p=new Params();
p.add("a","get_account");
p.add("account",account);
我需要自己构建这个功能吗,还是已经内置了什么


我正在使用Java 12。

我认为以下是使用Java 11实现这一点的最佳方法:

Map<String, String> parameters = new HashMap<>();
parameters.put("a", "get_account");
parameters.put("account", account);

String form = parameters.keySet().stream()
        .map(key -> key + "=" + URLEncoder.encode(parameters.get(key), StandardCharsets.UTF_8))
        .collect(Collectors.joining("&"));

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder().uri(URI.create(this.url))
        .headers("Content-Type", "application/x-www-form-urlencoded")
        .POST(BodyPublishers.ofString(form)).build();

HttpResponse<?> response = client.send(request, BodyHandlers.ofString());

System.out.println(response.statusCode() + response.body().toString());
Map参数=新的HashMap();
参数。put(“a”、“get_账户”);
参数。put(“account”,account);
字符串形式=parameters.keySet().stream()
.map(key->key+“=”+urlcoder.encode(parameters.get(key)、StandardCharsets.UTF_8))
.collect(收集器.连接(&));
HttpClient=HttpClient.newHttpClient();
HttpRequest request=HttpRequest.newBuilder().uri(uri.create(this.url))
.headers(“内容类型”、“应用程序/x-www-form-urlencoded”)
.POST(bodypublisher.ofString(form)).build();
HttpResponse response=client.send(请求,BodyHandlers.ofString());
System.out.println(response.statusCode()+response.body().toString());

这种方法很有用:

String param = Map.of("param1", "value1", "param2", "value2")
      .entrySet()
      .stream()
      .map(entry -> Stream.of(
               URLEncoder.encode(entry.getKey(), UTF_8),
               URLEncoder.encode(entry.getValue(), UTF_8))
                .collect(Collectors.joining("="))
      ).collect(Collectors.joining("&"));

通过
Map.of(…)
,最多可以使用10对(参数、值)。它返回一个不可修改的映射。

正如乌卡斯·奥尔舍夫斯基所说,工作正常:

String params = Map.of(
                    Constants.PARAM_CLIENT_ID, apiObject.getClientId(),
                    Constants.PARAM_SCOPE, apiObject.getScope(),
                    Constants.PARAM_CODE, apiObject.getCode(),
                    Constants.PARAM_REDIRECT_URI, apiObject.getRedirectUri(),
                    Constants.PARAM_GRANT_TYPE, apiObject.getGrantType(),
                    Constants.PARAM_CODE_VERIFIER, apiObject.getCodeVerifier())
                    .entrySet()
                    .stream()
                    .map(entry -> Stream.of(
                            URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8),
                            URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
                            .collect(Collectors.joining("="))
                    ).collect(Collectors.joining("&"));

HttpResponse<?> response = utils.consumeHttpPostFormUrlEncodedClientByRequestUrl(Constants.URL_BASE + Constants.URL_GET_TOKEN, params);
String params=Map.of(
Constants.PARAM_CLIENT_ID,apiObject.getClientId(),
Constants.PARAM_作用域,apiObject.getScope(),
Constants.PARAM_代码,apiObject.getCode(),
Constants.PARAM_REDIRECT_URI,apiObject.getRedirectUri(),
Constants.PARAM_GRANT_类型,apiObject.getGrantType(),
Constants.PARAM_CODE_验证器,apiObject.getCodeVerifier())
.entrySet()
.stream()
.map(条目->流程)(
URLEncoder.encode(entry.getKey(),StandardCharsets.UTF_8),
encode(entry.getValue(),StandardCharsets.UTF_8))
.collect(收集器.连接(“=”))
).collect(收集器.连接(&));
HttpResponse response=utils.consumeHttpPostFormUrlEncodedClientByRequestUrl(Constants.URL\u BASE+Constants.URL\u GET\u令牌,参数);
和ConsumerHttpPostFormUrlEncodedClientByRequestUrl

public HttpResponse<?> consumeHttpPostFormUrlEncodedClientByRequestUrl(String url, String map) throws IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
                .header("Content-Type", String.valueOf(MediaType.APPLICATION_FORM_URLENCODED))
                .POST(HttpRequest.BodyPublishers.ofString(map))
                .build();
        return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    }
公共HttpResponse ConsumerHttpPostFormUrlEncodedClientByRequestUrl(字符串url,字符串映射)引发IOException、InterruptedException{
HttpClient HttpClient=HttpClient.newHttpClient();
HttpRequest请求=HttpRequest.newBuilder(URI.create(url))
.header(“内容类型”,String.valueOf(MediaType.APPLICATION\u FORM\u URLENCODED))
.POST(HttpRequest.bodypublisher.ofString(map))
.build();
返回httpClient.send(request,HttpResponse.BodyHandlers.ofString());
}
退房。对于
x-www-form-urlencoded
body,它有一个很好的标签

var formBody=FormBodyPublisher.newBuilder()
.query(“a”、“获取账户”)
.查询(“账户”,账户)
.build();
var request=MutableRequest.POST(“https://example.com“,表格体);
//甲醇实现了一个HttpClient,它可以为您的请求/响应提供良好的服务。
//在这里,将为您添加内容类型标题。
var client=methodol.create();
var response=client.send(请求,BodyHandlers.ofString());

令人沮丧的是,你需要自己动手。自Java6.0以来,就出现了如下情况:您可以构建自己的BodyPublisher,它将地图接口作为输入