0

Trying to call an interface which accepts two POST parameters:

  • param1: string
  • param2: Array[string]

My attempt to post Array<String> as just a String is obviously naive, but can't find a better way. What would be the right way to post a parameter with the array of strings using Java 11 native 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());
}
Cray
  • 2,774
  • 7
  • 22
  • 32
Ninius86
  • 295
  • 6
  • 14

1 Answers1

0

Easier way could be, encode all the values as json, and parse (decode ) once you receive data in the server side. Cheers!

Pharsa Thapa
  • 326
  • 1
  • 9