Search code examples
javahttpclient

How to add parameter in request URL( Java 11)?


I'm absolute beginner in java. Trying to send some http request using the built in java httpclient.

How can I add the request parameters into the URI in such format:

parameter = hi
url = "https://www.url.com?parameter=hi"

With the code, I'm using, I can only set the headers but not the request parameters

    var client = HttpClient.newHttpClient();
    var request = HttpRequest.newBuilder(URI.create(url))
            .GET()
            .build();
    var reponse = client.send(request, HttpResponse.BodyHandlers.ofString());
    return reponse.body();

Thank you very much!


Solution

  • With native Java 11, it has to be done like you did. You need to add the parameters within the url parameter already. Or you need to create your own builder that allows you to append parameter.

    However, your requested behaviour is possible if you make use of libraries. One way to do it is to make use of Apache URIBuilder

        var client = HttpClient.newHttpClient();
        URI uri = new URIBuilder(httpGet.getURI())
                .addParameter("parameter", "hi")
                .build();
        var request = HttpRequest.newBuilder(uri)
                .GET()
                .build();
        var reponse = client.send(request, HttpResponse.BodyHandlers.ofString());
        return reponse.body();