0

尝试调用一个接受两个 POST 参数的接口:

  • 参数1:字符串
  • 参数2:数组[字符串]

我尝试Array<String>仅以字符串形式发布显然是幼稚的,但找不到更好的方法。使用 Java 11 本机 HttpClient 使用字符串数组发布参数的正确方法是什么?

public static HttpResponse<String> postRequest() throws IOException, InterruptedException {
    HttpClient httpClient = HttpClientSingleton.getInstance();

    Map<Object, Object> data = new HashMap<>();
    data.put("param1", "val1");
    data.put("param2", "[val21, val22, val23]");

    HttpRequest request = HttpRequest.newBuilder()
            .POST(ofFormData(data))
            .uri(URI.create("http://localhost:19990/test"))
            .build();
    return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}

public static HttpRequest.BodyPublisher ofFormData(Map<Object, Object> data) {
    var builder = new StringBuilder();
    for (Map.Entry<Object, Object> entry : data.entrySet()) {
        if (builder.length() > 0) {
            builder.append("&");
        }
        builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
        builder.append("=");
        builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
    }
    return HttpRequest.BodyPublishers.ofString(builder.toString());
}
4

1 回答 1

0

更简单的方法可能是将所有值编码为 json,并在服务器端接收到数据后解析(解码)。干杯!

于 2020-07-10T05:30:09.127 回答