Java MCQ: Which method is used to create a new instance of HttpClient in Java 11?
Answer:
Explanation:
The HttpClient.newHttpClient()
method is used to create a new instance of HttpClient
in Java 11. This method returns a default HttpClient
that can be used to send HTTP requests and receive HTTP responses. The HttpClient
created by this method is fully configured with default settings, and it can be customized further if needed by using a HttpClient.Builder
.
Here’s an example of creating an HttpClient
using newHttpClient()
:
import java.net.http.HttpClient;
public class HttpClientCreationExample {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
System.out.println("HttpClient created: " + client);
}
}
In this example, a new instance of HttpClient
is created using HttpClient.newHttpClient()
and is ready to be used for making HTTP requests.
The newHttpClient()
method simplifies the creation of HttpClient
instances, providing a convenient way to obtain a fully configured client with default settings.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html