在Java 9中有哪些不同的Http/2客户端类?

王林
王林 转载
2023-08-26 09:45:03 572浏览

在Java 9中有哪些不同的Http/2客户端类?

Http/2 Http 协议的较新版本。 Http/2 的改进包括关注数据在服务器和客户端之间的构建和传输方式。在这个新版本的Http/2协议中,为Http客户端、请求响应定义了单独的类强>。新的 API 使 Http 连接更容易维护、更快速,并且无需第三方库即可实现响应速度更快的应用程序。

新的 API 通过三个类处理 HTTP 连接。

  • HttpClient:它处理请求的创建和发送。
  • < strong>HttpRequest:它用于构造要通过HttpClient发送的请求。
  • HttpResponse:它保存已发送请求的响应。

在下面的代码片段中,我们需要向特定的 URL 发送请求并接收响应。

// Create an HttpClient object   
   HttpClient httpClient = HttpClient.newHttpClient();
   System.out.println(httpClient.version());

// Build a HTTPRequest
   HttpRequest httpRequest = HttpRequest.newBuilder().uri(new  URI("https://www.tutorialspoint.com/")).GET().build(); // create a GET request for the given URI
   Map<String, List<String>> headers = httpRequest.headers().map();
   headers.forEach((k, v) -> System.out.println(k + "-" + v));

// Send the request
   HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());

// Output the body of the response
   System.out.println("Response: " + httpResponse.body());

以上就是在Java 9中有哪些不同的Http/2客户端类?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除