Java Exercise
In this exercise, you will create a Java program that consumes an external REST API using the RestTemplate
or HttpClient
libraries. The program will make an HTTP GET request to a public API and process the response in JSON format. You will start by setting up your development environment, make the HTTP request to the API, and parse the response data to extract relevant information and display it in the console. This exercise will help you understand how to consume web services through REST APIs from Java applications.
Instructions:
- Set up your development environment and install the necessary dependencies to work with
RestTemplate
or HttpClient
.
- Make an HTTP GET request to a public API (for example, the JSONPlaceholder API or any other free API).
- Process the response into JSON format using a library such as
Jackson
or Gson
to map the data.
- Extract and display relevant information in the console, such as a user's name or post title.
- Add error handling to ensure the program properly handles connection failures or erroneous responses.
This This exercise will give you a solid understanding of how to consume REST APIs from Java, and how to handle responses in JSON format, an essential skill for integrating external web services into your applications.
View Example Code
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
public class RestApiConsumption {
public static void main(String[] args) {
// Create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();
// Public API URL
String url = "https://jsonplaceholder.typicode.com/posts/1";
// Perform the GET request and get the response as a String
ResponseEntity response = restTemplate.getForEntity(url, String.class);
// Print the response to the console
System.out.println("API Response:");
System.out.println(response.getBody());
}
}
Output:
API response:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit ...\nsequi ...\nvoluptatem ...."
}
This program makes an HTTP GET request to the JSONPlaceholder API, retrieves the data for the post with ID 1, and displays it in the console. The returned JSON includes details such as the post's userId
, id
, title
, and body
.