HTTP Requests in Java

We have many libraries in Java to make HTTP requests and get information from external API.

  1. HttpClient (Java Inbuilt since Java 9+)
  2. OkHttpClient
  3. Spring RestTemplate
  4. Spring WebClient

HttpClient

This is added in Java 9 and latest LTS that has is Java 11. To use this, first build a request then make a request.

// Build Request
HttpRequest request = HttpRequest.newBuilder()
        .header("Authorization", "Bearer "+accessToken)
        .uri(new URI("https://example.com/v1/api/employee"))
        .GET()
        .build();

// Make request
HttpResponse<String> response = HttpClient.newHttpClient()
        .send(request, HttpResponse.BodyHandlers.ofString());

// Convert response using ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(response.body(), UserInfo.class);

OkHttpClient

OkHttpClient is also similar to HttpClient and one of the popular one built by Square. Download latest version of the library from maven central. Version 4.10.0 is the latest version as of the writing

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.10.0</version>
</dependency>

and build the request as follows

// Build Request
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://example.com/v1/api/employee")
        .addHeader("Authorization", "Bearer "+accessToken)
        .build();

// Make request
var response = client.newCall(request).execute();

// Convert using ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(response.body().string(), UserInfo.class);

Spring RestTemplate

If you are using Spring MVC framework, then you can use Spring RestTemplate to make synchronous requests. Before making the request create RestTemplate object. You can create is via `new RestTemplate()` or define a bean in config file

// Create RestTemplate object with defaults
var restTemplate = new RestTemplate();

// Build headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token);
var httpEntity=HttpEntity<>(headers);

// Make request
HttpEntity<UserInfo> response =
        restTemplate.exchange("https://example.com/v1/api/employee", GET, httpEntity, UserInfo.class);

// RestTemplate converts response to given object type
var userInfo=response.getBody();

Spring WebClient

Spring WebClient helps to make asynchronous and synchronous requests. Before making the request, create WebClient object or define a bean

// Get WebClient
var uriSpec = webClient.get().uri("https://example.com/v1/api/employee");

// Add Auth Headers
uriSpec.headers(httpHeaders -> httpHeaders.add("Authorization", "Bearer " + token));

// Make request and get Response
uriSpec.retrieve().bodyToMono(UserInfo.class).block();
Pavan Kumar Jadda
Pavan Kumar Jadda
Articles: 10

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.