4

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.

daniel
  • 2,665
  • 1
  • 8
  • 18
John Little
  • 10,707
  • 19
  • 86
  • 158
  • 1
    Is there a reason you weren't able to find this in the docs? https://openjdk.java.net/groups/net/httpclient/recipes.html#post https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.Builder.html#POST(java.net.http.HttpRequest.BodyPublisher) – Michael Apr 12 '21 at 11:04
  • 1
    Thanks for the reply. The links you included are both posts, not GET. I need to set get params. I can manually add them to the URL string one by one, doing the required encoding, but this is pretty tedious, and I would assume there is a method for this? – John Little Apr 12 '21 at 11:15
  • Go to the 2nd link and scroll down slightly – Michael Apr 12 '21 at 11:19
  • use URIBuilder: https://www.baeldung.com/java-httpclient-parameters#add-parameters-to-httpclient-requests-using-uribuilder – Marc Stroebel Apr 12 '21 at 12:00
  • Unfortunately URIBuilder is the apache HTTP library not the java 11 built in one. We cant use the apache one as it breaks AEM if included as a maven dependency,. – John Little Apr 12 '21 at 21:05

1 Answers1

2

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();
konka
  • 21
  • 3