What are the different ways to write clients for RESTful calls in java applications?

What are the different ways to write clients for RESTful calls in java applications?

To write clients for RESTful calls in Java applications, you can use several methods ranging from built-in libraries to third-party frameworks. The choice often depends on the project’s complexity, performance requirements, and preferred coding style.

Built-in Java Libraries

java.net.HttpURLConnection

This is the oldest and most fundamental way to make HTTP calls in Java. It’s part of the standard library, so no external dependencies are needed. HttpURLConnection provides fine-grained control over the request and response lifecycle, allowing you to set headers, handle redirects, and manage connections. However, it’s quite verbose and low-level, requiring a lot of boilerplate code for simple tasks.

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class HttpURLConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://api.example.com/data");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response.toString());
        }
    }
}

Third-Party Libraries and Frameworks

Apache HttpClient

A popular and robust library that offers a more feature-rich and developer-friendly API than HttpURLConnection. It provides comprehensive support for complex HTTP features like connection pooling, authentication, and request/response interceptors. It’s a great choice for production-grade applications that need extensive control over their HTTP communication.

This is a series of posts showing various things we can do using httpclient - https://www.baeldung.com/httpclient-guide

OkHttp

Developed by Square, OkHttp is a modern, efficient, and very popular HTTP client. It’s known for its simplicity, performance, and features like HTTP/2 support, connection pooling, and transparent GZIP compression. It’s widely used in Android development and has gained significant traction in backend Java applications for its ease of use and performance.

Spring’s RestTemplate

Spring RestTemplate

This is a synchronous client provided by the Spring Framework. RestTemplate simplifies REST calls by handling many low-level details. It supports object mapping, so you can directly convert JSON or XML responses into Java objects without manual parsing. While widely used, Spring has now officially deprecated it in favor of the more modern and non-blocking WebClient.

Spring’s WebClient

Spring WebFlux

Part of the Spring WebFlux module, WebClient is a modern, non-blocking, and reactive HTTP client. It’s the recommended way to make REST calls in Spring applications, especially when dealing with high concurrency and performance-critical systems. It leverages Project Reactor to handle asynchronous communication efficiently.

import org.springframework.web.reactive.function.client.WebClient;

public class WebClientExample {
    public static void main(String[] args) {
        WebClient client = WebClient.create("https://api.example.com");
        client.get()
              .uri("/data")
              .retrieve()
              .bodyToMono(String.class)
              .subscribe(response -> System.out.println(response));
    }
}

Declarative Clients

Feign

Often used with Spring Cloud, Feign is a declarative REST client. You define an interface with annotations that map to REST endpoints, and Feign automatically generates the implementation. This approach significantly reduces boilerplate code, making your client code clean and easy to read.

@FeignClient(name = "api-service")
public interface ApiServiceClient {
    @GetMapping("/data")
    String getData();
}

This interface, when used with Spring, would be automatically implemented to make the GET call to the specified service.

TODO

https://www.baeldung.com/spring-boot-feignclient-vs-webclient

Retrofit

A type-safe HTTP client for Java and Android, also developed by Square. Similar to Feign, Retrofit uses annotations on an interface to describe the REST endpoints. It handles the network requests and serializes the response into Plain Old Java Objects (POJOs). It’s highly popular in the Android community and is a great choice for any Java application needing a clean, declarative client.

Spring web frameworks

  1. Web Servlet - Spring MVC, WebSocket, SockJS, STOMP Messaging: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#spring-web
  2. Web Reactive - Spring WebFlux, WebClient, WebSocket, RSocket: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#spring-webflux

KNOWLEDGE GAP - LEARN MORE

  1. Compare various ways of writing web service clients:
    1. rest template,
    2. webflux client and
    3. feign client

Tags

  1. Generate server and client code from OpenAPI specification file

Links to this note