An improved HttpClient API was launched in Java 9 as an experimental attribute. With Java 11, now HttpClient may be a standard. it's recommended to use rather than other HTTP Client APIs such as Apache HTTP Client API. It's quite attributed rich and also from now, onwards Java-based applications can easily make HTTP requests without making use of any external dependency.
Steps to use an HttpClient are given below:
Example
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class APITester { public static void main(String[] args) { HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); try { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create("https://www.google.com")) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Headers: " + response.headers().allValues("content-type")); System.out.println("Body: " + response.body()); } catch (IOException ' InterruptedException e) { e.printStackTrace(); } } }
Output
Your response must look like this:
Status code: 200 Headers: [text/html; charset=ISO-8859-1] Body: <!doctype html> ... </html>