Making HTTP request in Java
Using java.net package
Last updated on
When doing microservices development in Java, it is common that we need to call an HTTP
request to another server. In Spring Boot application, we can use the RestTemplate
,
as shown in this article.
In this blog, we mainly focus on the approach using only vanilla Java packages. We use utils from java.net package, but the usage is a bit more complicated than other frameworks (such as axios in JavaScript). Here is a code snippet for quick reference.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/* ... */
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080/api/v1/aRandomAPI"))
.POST(HttpRequest.BodyPublishers.ofString(new GsonBuilder()
.setPrettyPrinting()
.create()
.toJson(aRandomObject)))
.setHeader("Content-Type", "application/json")
.build();
try {
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
ResponseClass responseBody = new Gson()
.fromJson(response.body(),
ResponseClass.class);
return responseBody;
} catch (Exception e) {
return null;
}
/* ... */