The newHttpClient() method in Java is a factory method in the java.net.http.HttpClient class that creates a new HttpClient instance with default settings. The HttpClient class was introduced in Java 11 as part of the Java HTTP Client API, which provides an efficient and flexible way to send HTTP requests and receive responses.
Table of Contents
- Introduction
newHttpClient()Method Syntax- Examples
- Basic Usage of
newHttpClient() - Making a GET Request to a Dummy API
- Making a POST Request to a Dummy API
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The HttpClient.newHttpClient() method simplifies the process of creating an HTTP client for sending requests and handling responses. The default HttpClient instance is created with default configurations, including the default executor, default protocol version (HTTP/2), and default redirect policy (never follow redirects automatically).
newHttpClient() Method Syntax
The syntax for the newHttpClient() method is as follows:
public static HttpClient newHttpClient()
Returns:
- A new
HttpClientinstance with default settings.
Examples
Basic Usage of newHttpClient()
The following example demonstrates how to create a new HttpClient instance using the newHttpClient() method.
Example
import java.net.http.HttpClient;
public class HttpClientExample {
public static void main(String[] args) {
// Create a new HttpClient instance
HttpClient httpClient = HttpClient.newHttpClient();
// Display the default settings of the HttpClient
System.out.println("HttpClient created with default settings:");
System.out.println("Protocol Version: " + httpClient.version());
System.out.println("Redirect Policy: " + httpClient.followRedirects());
}
}
Output:
HttpClient created with default settings:
Protocol Version: HTTP_2
Redirect Policy: NEVER
Making a GET Request to a Dummy API
The following example demonstrates how to use the HttpClient 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;
public class HttpClientGetExample {
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 (Exception 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"
}
Making a POST Request to a Dummy API
The following example demonstrates how to use the HttpClient to make a POST 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.net.http.HttpRequest.BodyPublishers;
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 (Exception 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. -
JSON Handling: The examples demonstrate 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 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;
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 (Exception 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
HttpClientto 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.newHttpClient() method is used for creating HTTP clients in Java. It simplifies the process of sending HTTP 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.