Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parameters to java.net.http.HttpClient GET request?

We found the following example, which works:

import java.net.http.HttpClient;
:
private static final HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1)
        .connectTimeout(Duration.ofSeconds(TIMEOUT)).build();
:
public String getStuff(HashMap<String,String> params) {
    HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create("https://httpbin.org/get"))
            .setHeader("User-Agent", "My Agent v1.0")
            .build();
    
    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
   return response.body();
}

The question is how do we get the params into the request? We could manually put them in the URI by string manipulation, but this wont work for POST.

We would expect a setParameter method similar to setHeader, but this doesnt exist (according to eclipse at least).

For now I am doing it manually thusly:

    String uri = "http://Somesite.com/somepath";
    if (params != null) {
        uri += "?";
        for (String key : params.keySet()) {
            uri += "" + key + "=" + params.get(key);
          }
    }

    HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(uri))
            .setHeader("User-Agent", agent)
            .build();

Presumably for POST ill have to manually construct a body with the post params structure.

like image 909
John Little Avatar asked Oct 29 '25 17:10

John Little


2 Answers

Use javax.ws.rs.core.UriBuilder It has queryParam method. e.g.:

UriBuilder.fromLink( Link.fromUri( "somehost" ).build() )
            .path( API_SERVICES )
            .queryParam( "path", path)
            .queryParam( "method", method )
            .build();
like image 80
konka Avatar answered Oct 31 '25 08:10

konka


Use javax.ws.rs.core.UriBuilder It has queryParam method. e.g.:

UriBuilder.fromLink( Link.fromUri( "somehost" ).build() )
            .path( API_SERVICES )
            .queryParam( "path", path)
            .queryParam( "method", method )
            .build();
like image 39
konka Avatar answered Oct 31 '25 08:10

konka



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!