English 中文(简体)
Java 11 - Standard HttpClient
  • 时间:2024-12-22

Java 11 - Standard HttpCpent


Previous Page Next Page  

An enhanced HttpCpent API was introduced in Java 9 as an experimental feature. With Java 11, now HttpCpent is a standard. It is recommended to use instead of other HTTP Cpent APIs pke Apache Http Cpent API. It is quite feature rich and now Java based apppcations can make HTTP requests without using any external dependency.

Steps

Following are the steps to use an HttpCpent.

    Create HttpCpent instance using HttpCpent.newBuilder() instance

    Create HttpRequest instance using HttpRequest.newBuilder() instance

    Make a request using httpCpent.send() and get a response object.

Example


import java.io.IOException;
import java.net.URI;
import java.net.http.HttpCpent;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

pubpc class APITester {
   pubpc static void main(String[] args) {
      HttpCpent httpCpent = HttpCpent.newBuilder()
         .version(HttpCpent.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 = httpCpent.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

It will print the following output.


Status code: 200
Headers: [text/html; charset=ISO-8859-1]
Body: <!doctype html>
...
</html>
Advertisements