Java MCQ: How does the sendAsync() method in Java 11 HttpClient differ from the send() method?
Answer:
Explanation:
The sendAsync()
method in Java 11 HttpClient
sends HTTP requests asynchronously, returning a CompletableFuture
. This method allows the client to continue executing other tasks while waiting for the HTTP response, making it suitable for non-blocking operations where the response can be processed later when it becomes available.
Here’s an example of using sendAsync()
:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class HttpClientSendAsyncExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://www.example.com"))
.build();
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
// Do other tasks while the request is being processed
HttpResponse<String> response = futureResponse.join();
System.out.println("Response status code: " + response.statusCode());
System.out.println("Response body: " + response.body());
}
}
In this example, sendAsync()
sends the request and immediately returns a CompletableFuture
. The program can continue executing other code, and the response can be accessed later using futureResponse.join()
.
The sendAsync()
method is ideal for scenarios where you want to avoid blocking the main thread, making it suitable for applications that require high concurrency or need to perform other tasks while waiting for the HTTP response.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html