URL Encoded POST Request Java 11

Sending a POST request using HTTP REST Client. url-encoded send POST requests with x-www-form-urlencoded parameters

In this article, we will understand how to send POST request using new Http Client Library in Java 11.

RequestBuilder for POST request

POST request requires a body in contrast to a GET request. Java 11 HttpClient has a good api to call post requests. The only different between GET request and POST request is the use of RequestBuilder.

The RequestBuilder object is constructed using the builder pattern. In the below example we have added a single form parameter to the api request.

HttpRequest.RequestBuilder builder = HttpRequest.newBuilder()
        .uri(new URI(targetUrl))
        .POST(urlParameters)
        .headers("Content-Type", "application/x-www-form-urlencoded");

HttpRequest request = builder.build();

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

System.out.println(response.statusCode() + " " + response.body().toString());

The above request send the POST request with content type application/x-www-form-urlencoded.

headers() method in a variable argument method. All the headers can be passed in the same method.

Final Code


package com.metamug.apitester.http;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

public class APIClient {
    HttpClient client;

    public APIClient(){
        client = HttpClient.newHttpClient();
    }

    public HttpResponse<String> call(String url, Map<String, String> params) throws URISyntaxException, IOException, InterruptedException {

        HttpRequest request = HttpRequest.newBuilder()
            .uri(new URI(url))
            .POST(getParamsUrlEncoded(params))
            .headers("Content-Type", "application/x-www-form-urlencoded")
            .build();
        System.getLogger("").log(System.Logger.Level.INFO, request.toString());
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response;
    }

    private HttpRequest.BodyPublisher getParamsUrlEncoded(Map<String, String> parameters) {
        String urlEncoded = parameters.entrySet()
                            .stream()
                            .map(e -> e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
                            .collect(Collectors.joining("&"));
        return HttpRequest.BodyPublishers.ofString(urlEncoded);
    }

}

No dependency and closing the client

Java 11 HttpClient works out of the box in Java 11 and above, so no need of adding any dependency in the project. No need to close the requests as each HttpClient spawn a daemon thread called selmgr which supposed to take care of in fly requests. This thread will be closed when there is no reference to the HttpClient in the code.