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.