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.

5
  • 1
    Is there a reason you weren't able to find this in the docs? openjdk.java.net/groups/net/httpclient/recipes.html#post docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/… Commented Apr 12, 2021 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? Commented Apr 12, 2021 at 11:15
  • Go to the 2nd link and scroll down slightly Commented Apr 12, 2021 at 11:19
  • use URIBuilder: baeldung.com/… Commented Apr 12, 2021 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,. Commented Apr 12, 2021 at 21:05

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.