I am going to make a RESTful call in Java. However, I don't know how to make the call. Do I need to use the URLConnection or others?
I am going to make a RESTful call in Java. However, I don't know how to make the call. Do I need to use the URLConnection or others?
I see many answers, here's what we are using in 2020 WebClient, and BTW RestTemplate is going to get deprecated. (can check this) RestTemplate going to be deprecated
The following is an example of a GET request that prints the response body as a String with HttpRequest:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.org/"))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
If you need to set the header you could use the following method inside the HttpRequest.Builder:
.setHeader("api-key", "value")
Here is a utility class I use for calling some internal APIs (Sept 2022). All core java except for Gson for the Json de/serialization. POST and GET.
package com.somepackagename.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
public class HTTPCaller {
private final String BEARER_TOKEN;
private static Gson gson = new GsonBuilder().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
public HTTPCaller(String bearerToken) {
this.BEARER_TOKEN = bearerToken;
}
public Map<String, Object> post(String endpoint, String jsonPayload, Map<String, String> headers)
throws IOException, URISyntaxException, InterruptedException {
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder();
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
reqBuilder.header(header.getKey(), header.getValue());
}
}
//always add these anyway, or not
reqBuilder.header("content-type", "application/json")
.header("Authorization", "Bearer " + BEARER_TOKEN);
HttpRequest request = reqBuilder
.uri(new URI(endpoint))
.POST(HttpRequest.BodyPublishers.ofByteArray(jsonPayload.getBytes()))
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
String responseBody = response.body();
Map<String, Object> output = (Map<String, Object>) gson.fromJson(responseBody, HashMap.class);
return output;
}
public Map<String, Object> get(String endpoint) throws Exception {
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder();
//always add these anyway
reqBuilder.header("content-type", "application/json")
.header("Authorization", "Bearer " + BEARER_TOKEN);
HttpRequest request = reqBuilder
.uri(new URI(endpoint))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
String responseBody = response.body();
Map<String, Object> output = (Map<String, Object>) gson.fromJson(responseBody, HashMap.class);
return output;
}
}