What is the return type of the send() method in the Java 11 HttpClient class?

Java MCQ: What is the return type of the send() method in the Java 11 HttpClient class?

a) HttpResponse
b) String
c) Future
d) void

Answer:

a) HttpResponse

Explanation:

The send() method in the Java 11 HttpClient class returns an instance of HttpResponse. This method is used to send an HTTP request synchronously, meaning that it blocks until the response is received. The returned HttpResponse object contains information about the response, including the status code, headers, and body.

Here’s an example of using the send() method:

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

public class HttpClientSendExample {
    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 status code: " + response.statusCode());
        System.out.println("Response body: " + response.body());
    }
}

In this example, the send() method is used to send a GET request, and the returned HttpResponse object provides access to the status code and body of the response.

The send() method is ideal for scenarios where you need to wait for the response before proceeding, making it suitable for simple, blocking HTTP requests.

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