Java 11: New HTTP client send POST requests with x-www-form-urlencoded parameters

Doua Beri picture Doua Beri · Jun 24, 2019 · Viewed 8.4k times · Source

I'm trying to send a POST request using the new http client api. Is there a built in way to send parameters formatted as x-www-form-urlencoded ?

My current code:

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();

What I'm looking is for a better way to pass the parameters. Something like this:

Params p=new Params();
p.add("a","get_account");
p.add("account",account);

Do I need to build myself this functionality or is something already built in?

I'm using Java 12.

Answer

deloyar picture deloyar · Jun 23, 2020

I think the following is the best way to achieve this using 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());