The send() method in Java is an abstract method provided by the java.net.http.HttpClient class. It is used to send a given HttpRequest and receive an HttpResponse. This method blocks the calling thread until the response is available, making it suitable for synchronous HTTP communication.
Table of Contents
- Introduction
send()Method Syntax- Examples
- Basic Usage of
send() - Handling Different Response Types
- Sending a POST Request with JSON Payload
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The HttpClient.send() method allows you to perform synchronous HTTP requests and receive responses. It supports handling different types of response bodies using HttpResponse.BodyHandler<T>. This method is useful when you need to perform HTTP operations that require a blocking call, where you wait for the response before proceeding with other tasks.
send() Method Syntax
The syntax for the send() method is as follows:
public abstract <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) throws IOException, InterruptedException
Parameters:
request: TheHttpRequestto be sent.responseBodyHandler: TheHttpResponse.BodyHandler<T>that handles the response body.
Returns:
- An
HttpResponse<T>containing the response data.
Throws:
IOException: If an I/O error occurs when sending or receiving.InterruptedException: If the operation is interrupted.
Examples
Basic Usage of send()
The following example demonstrates how to use the send() method to make a GET request to a dummy API and handle the response.
Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
public class HttpClientSendExample {
public static void main(String[] args) {
// Create a new HttpClient instance
HttpClient httpClient = HttpClient.newHttpClient();
// Define the URI for the GET request
String url = "https://jsonplaceholder.typicode.com/posts/1";
// Create an HttpRequest for the specified URI
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
// Send the request and handle the response
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// Display the response status code and body
System.out.println("Response Status Code: " + response.statusCode());
System.out.println("Response Body:");
System.out.println(response.body());
} catch (IOException | InterruptedException e) {
System.out.println("Error occurred while making GET request: " + e.getMessage());
}
}
}
Output:
Response Status Code: 200
Response Body:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Handling Different Response Types
The following example demonstrates how to handle different types of response bodies using HttpResponse.BodyHandlers.
Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class HttpClientResponseTypesExample {
public static void main(String[] args) {
// Create a new HttpClient instance
HttpClient httpClient = HttpClient.newHttpClient();
// Define the URI for the GET request
String url = "https://jsonplaceholder.typicode.com/posts/1";
// Create an HttpRequest for the specified URI
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
// Handle response as a string
handleStringResponse(httpClient, request);
// Handle response as a byte array
handleByteArrayResponse(httpClient, request);
// Handle response as an input stream
handleInputStreamResponse(httpClient, request);
}
private static void handleStringResponse(HttpClient httpClient, HttpRequest request) {
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("\nString Response:");
System.out.println("Status Code: " + response.statusCode());
System.out.println("Body: " + response.body());
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void handleByteArrayResponse(HttpClient httpClient, HttpRequest request) {
try {
HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
System.out.println("\nByte Array Response:");
System.out.println("Status Code: " + response.statusCode());
System.out.println("Body Length: " + response.body().length);
// Convert byte array to string for demonstration
String responseBody = new String(response.body(), StandardCharsets.UTF_8);
System.out.println("Body (as String): " + responseBody);
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void handleInputStreamResponse(HttpClient httpClient, HttpRequest request) {
try {
HttpResponse<InputStream> response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
System.out.println("\nInput Stream Response:");
System.out.println("Status Code: " + response.statusCode());
// Read the InputStream (converting it to a String here for demonstration)
InputStream inputStream = response.body();
String responseBody = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println("Body: " + responseBody);
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
String Response:
Status Code: 200
Body: {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Byte Array Response:
Status Code: 200
Body Length: 292
Body (as String): {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Input Stream Response:
Status Code: 200
Body: {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Sending a POST Request with JSON Payload
The following example demonstrates how to use the send() method to make a POST request with a JSON payload to a dummy API and handle the response.
Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.io.IOException;
public class HttpClientPostExample {
public static void main(String[] args) {
// Create a new HttpClient instance
HttpClient httpClient = HttpClient.newHttpClient();
// Define the URI for the POST request
String url = "https://jsonplaceholder.typicode.com/posts";
// Create a JSON string for the request body
String jsonRequestBody = """
{
"title": "foo",
"body": "bar",
"userId": 1
}
""";
// Create an HttpRequest for the specified URI with POST method
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(jsonRequestBody))
.build();
// Send the request and handle the response
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// Display the response status code and body
System.out.println("Response Status Code: " + response.statusCode());
System.out.println("Response Body:");
System.out.println(response.body());
} catch (IOException | InterruptedException e) {
System.out.println("Error occurred while making POST request: " + e.getMessage());
}
}
}
Output:
Response Status Code: 201
Response Body:
{
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}
Explanation:
-
GET Request: The
HttpClientsends a GET request to the specified URL, retrieves the response, and displays the status code and response body. -
POST Request: The
HttpClientsends a POST request with a JSON payload to the specified URL, retrieves the response, and displays the status code and response body. -
Response Types: The examples demonstrate handling different types of response bodies using
HttpResponse.BodyHandlers. -
JSON Handling: The examples show how to handle JSON data in HTTP requests, including setting the appropriate content type and handling the response body.
Real-World Use Case
Fetching Data from a REST API
In real-world applications, the HttpClient.send() method can be used to fetch data from REST APIs and integrate it into your application. For example, you might want to fetch weather data from an online API and display it in your application.
Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class WeatherApiExample {
public static void main(String[] args) {
// Create a new HttpClient instance
HttpClient httpClient = HttpClient.newHttpClient();
// Define the URI for the weather API
String apiKey = "your_api_key";
String city = "London";
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey;
// Create an HttpRequest for the specified URI
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
// Send the request and handle the response
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// Parse the JSON response using Jackson
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonResponse = objectMapper.readTree(response.body());
// Extract and display weather information
String weatherDescription = jsonResponse.at("/weather/0/description").asText();
double temperature = jsonResponse.at("/main/temp").asDouble() - 273.15; // Convert Kelvin to Celsius
System.out.println("Weather in " + city + ": " + weatherDescription);
System.out.println("Temperature: " + String.format("%.2f", temperature) + "°C");
} catch (IOException | InterruptedException e) {
System.out.println("Error occurred while fetching weather data: " + e.getMessage());
}
}
}
Note: Replace "your_api_key" with your actual API key from OpenWeatherMap.
Explanation:
-
Weather Data Fetching: The example demonstrates how to use the
HttpClient.send()method to fetch weather data from an online API and parse the JSON response using the Jackson library. -
Data Integration: The fetched data is integrated into the application and displayed to the user.
-
JSON Parsing: The example shows how to parse JSON data and extract specific information using the Jackson library.
Conclusion
The HttpClient.send() method is used for performing synchronous HTTP requests in Java. It simplifies the process of sending requests and handling responses, making it easier to integrate web-based data into your applications. By using the HttpClient API, you can efficiently interact with REST APIs, fetch data, and process it in your Java applications.