What is the primary use of the Java HTTP Client introduced in Java 11?

Java MCQ: What is the primary use of the Java HTTP Client introduced in Java 11?

a) To create TCP connections
b) To send and receive HTTP requests and responses
c) To manage WebSocket connections
d) To encrypt data over a network

Answer:

b) To send and receive HTTP requests and responses

Explanation:

The primary use of the Java HTTP Client, introduced in Java 11, is to send and receive HTTP requests and responses. The java.net.http.HttpClient class provides a modern, non-blocking API for performing HTTP operations, replacing the older HttpURLConnection class. It supports both synchronous and asynchronous communication and can handle HTTP/1.1 and HTTP/2 protocols.

Here’s a simple example of using the HttpClient to send an HTTP GET request:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                                         .uri(new URI("https://www.example.com"))
                                         .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

In this example, HttpClient is used to send a GET request to https://www.example.com, and the response body is printed to the console. The HttpClient provides a straightforward and efficient way to interact with HTTP services.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top