Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 720
do-it-yourself Avatar asked Apr 01 '26 19:04

do-it-yourself


2 Answers

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

   //import org.apache.http.client.utils.URIBuilder;
   //import org.apache.http.client.HttpClient;

    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();
like image 148
Yoni Avatar answered Apr 03 '26 07:04

Yoni


You don't have methods for adding parameters, but you can use String.format() to format the URL nicely.

final static String URL_FORMAT = "http://url.com?%s=%s";
final String request = String.format(URL_FORMAT, "paramater", "hi");
like image 32
Ahmed Rezk Avatar answered Apr 03 '26 09:04

Ahmed Rezk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!