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

Dou*_*eri 5 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(BodyPublishers.ofString("a=get_account&account=" + URLEncoder.encode(account, "UTF-8")))
        .build();
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种传递参数的更好方法。像这样:

Params p=new Params();
p.add("a","get_account");
p.add("account",account);
Run Code Online (Sandbox Code Playgroud)

我需要自己构建此功能还是已经内置了某些功能?

我正在使用Java 12。

小智 10

我认为以下是使用 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());
Run Code Online (Sandbox Code Playgroud)


小智 5

正如 \xc5\x81ukasz Olszewski 所说,工作正常:

\n
String params = Map.of(\n                    Constants.PARAM_CLIENT_ID, apiObject.getClientId(),\n                    Constants.PARAM_SCOPE, apiObject.getScope(),\n                    Constants.PARAM_CODE, apiObject.getCode(),\n                    Constants.PARAM_REDIRECT_URI, apiObject.getRedirectUri(),\n                    Constants.PARAM_GRANT_TYPE, apiObject.getGrantType(),\n                    Constants.PARAM_CODE_VERIFIER, apiObject.getCodeVerifier())\n                    .entrySet()\n                    .stream()\n                    .map(entry -> Stream.of(\n                            URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8),\n                            URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))\n                            .collect(Collectors.joining("="))\n                    ).collect(Collectors.joining("&"));\n\nHttpResponse<?> response = utils.consumeHttpPostFormUrlEncodedClientByRequestUrl(Constants.URL_BASE + Constants.URL_GET_TOKEN, params);\n
Run Code Online (Sandbox Code Playgroud)\n

和 ConsumerHttpPostFormUrlEncodedClientByRequestUrl

\n
public HttpResponse<?> consumeHttpPostFormUrlEncodedClientByRequestUrl(String url, String map) throws IOException, InterruptedException {\n        HttpClient httpClient = HttpClient.newHttpClient();\n        HttpRequest request = HttpRequest.newBuilder(URI.create(url))\n                .header("Content-Type", String.valueOf(MediaType.APPLICATION_FORM_URLENCODED))\n                .POST(HttpRequest.BodyPublishers.ofString(map))\n                .build();\n        return httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n    }\n
Run Code Online (Sandbox Code Playgroud)\n