Consuming RESTful web services from a Java application allows you to interact with external systems and APIs. It involves sending HTTP requests (GET, POST, PUT, DELETE) to a web service and processing the responses. In this article, we will explore how to consume RESTful web services in Java using the HttpURLConnection
class, the HttpClient
library, and the RestTemplate
class in Spring.
REST (Representational State Transfer) is a popular architectural style used for designing networked applications. RESTful web services are based on HTTP and are stateless, meaning each request from a client to a server must contain all the information needed to understand the request.
In Java, there are several ways to consume RESTful web services, including using the standard HttpURLConnection
class, the HttpClient
API (Java 11+), or Spring's RestTemplate
class. Each method allows you to make HTTP requests and handle responses.
HttpURLConnection
HttpURLConnection
is a part of the Java standard library and can be used to send HTTP requests and receive responses. Below is an example of how to consume a RESTful web service using HttpURLConnection
:
HttpURLConnection
to Consume a RESTful Web Service
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestClient {
public static void main(String[] args) throws Exception {
String url = "https://api.example.com/data"; // Replace with actual API URL
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Set HTTP method to GET
con.setRequestMethod("GET");
// Get response code
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print the response
System.out.println("Response: " + response.toString());
}
}
In this example, we create an HttpURLConnection
object to send a GET request to a RESTful API. We then read and print the response from the server. The response code is also captured to verify the success of the request.
HttpClient
Starting from Java 11, the HttpClient
API provides a more modern and efficient way to send HTTP requests. It supports both synchronous and asynchronous communication, and is a better alternative to HttpURLConnection
.
HttpClient
to Consume a RESTful Web Service
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpHeaders;
public class RestClient {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data")) // Replace with actual API URL
.build();
// Send the request and get the response
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Print the response code and body
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response: " + response.body());
}
}
This example demonstrates how to use the HttpClient
to send a GET request and retrieve the response body as a string. The HttpResponse
object contains the status code, headers, and body of the response.
RestTemplate
(Spring)For Spring-based applications, RestTemplate
is a convenient class for making HTTP requests. It is highly customizable and supports both synchronous and asynchronous requests. In Spring 5, WebClient
is introduced as a non-blocking, reactive alternative to RestTemplate
, but RestTemplate
remains widely used in many applications.
RestTemplate
to Consume a RESTful Web Service
import org.springframework.web.client.RestTemplate;
public class RestClient {
public static void main(String[] args) {
String url = "https://api.example.com/data"; // Replace with actual API URL
RestTemplate restTemplate = new RestTemplate();
// Send GET request and retrieve response
String response = restTemplate.getForObject(url, String.class);
// Print the response
System.out.println("Response: " + response);
}
}
In this example, we use the RestTemplate
class from Spring to send a GET request and receive the response as a string. The getForObject()
method is used to fetch the response directly into the specified class (in this case, String.class
).
In addition to GET requests, RESTful web services support other HTTP methods like POST, PUT, and DELETE. These methods can be used to create, update, and delete resources on the server.
RestTemplate
to Handle POST and PUT Requests
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
public class RestClient {
public static void main(String[] args) {
String url = "https://api.example.com/data"; // Replace with actual API URL
RestTemplate restTemplate = new RestTemplate();
// Prepare headers and body for POST request
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
String requestBody = "{\"name\":\"John Doe\",\"age\":30}";
HttpEntity entity = new HttpEntity<>(requestBody, headers);
// Send POST request
String postResponse = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
System.out.println("POST Response: " + postResponse);
// Prepare data for PUT request
String updatedData = "{\"name\":\"John Doe\",\"age\":31}";
// Send PUT request
String putResponse = restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity<>(updatedData, headers), String.class).getBody();
System.out.println("PUT Response: " + putResponse);
}
}
In this example, we use RestTemplate
to send POST and PUT requests. For both methods, we need to include the request body, which is typically sent as JSON. The HttpEntity
class is used to wrap the request data and headers.
Consuming RESTful web services in Java is straightforward using the HttpURLConnection
class, Java 11's HttpClient
API, or Spring's RestTemplate
. Each of these methods offers different levels of functionality and convenience, depending on the requirements of your project. By understanding how to use these tools, you can easily integrate your Java application with external RESTful APIs, enabling powerful interactions between systems.