Java 9 中有哪些不同的 Http/2 客户端类?
javaobject oriented programmingprogramming更新于 2025/9/11 21:00:17
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://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 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

