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


Http/2 Http 协议的更新版本。Http/2的改进包括专注于数据如何以框架形式表示并在服务器与客户端之间传输。在这个 Http/2 协议新版本中,Http 客户端、请求响应分别定义在各自独立的类中。新的 API 使得Http 连接更易于维护,速度更快,并且无需借助第三方库即可支持响应速度更快的应用程序。

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

  • HttpClient:该类用于处理创建和发送请求。
  • 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://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());

更新于: 2020 年 3 月 25 日

128 次浏览

开启你的职业

完成课程,获得认证

马上开始
广告
© . All rights reserved.