Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Http/2 Client ใน Java 9 คืออะไร

Http/2 Client API นำมารวมใน Java 9 มีปรับปรุงประสิทธิภาพมากกว่า Http/1.1 และรองรับ server-side push events ทำให้เว็บไซต์ มีประสิทธิภาพ และ เร็วขึ้น Http/2 Client เป็น incubator module ชื่อ jdk.incubator.httpclient หมายถึงฟีเจอร์ยังไม่ final อาจมีการเปลี่ยนแปลงในเวอร์ชันอนาคต export package jdk.incubator.http ที่มี public APIs ทั้งหมด

การใช้งาน Http/2 Client

ต้องใช้ incubator module ส่ง httpclient module เข้า JShell ด้วย "--add-modules"

C:\>jshell -v --add-modules jdk.incubator.httpclient
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

ตัวอย่างใน JShell

jshell> import jdk.incubator.http.*;
jshell> HttpClient httpClient = HttpClient.newHttpClient();
httpClient ==> jdk.incubator.http.HttpClientImpl@534df152
| created variable httpClient : HttpClient

jshell> HttpRequest httpRequest = HttpRequest.newBuilder()
   ...>     .uri(new URI("https://www.google.com"))
   ...>     .GET()
   ...>     .build();
httpRequest ==> https://www.google.com GET
| created variable httpRequest : HttpRequest

jshell> HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());
httpResponse ==> jdk.incubator.http.HttpResponseImpl@609cd4d8
| created variable httpResponse : HttpResponse

jshell> System.out.println(httpResponse.statusCode());
403

jshell> System.out.println(httpResponse.body());
Apache HTTP Server Test Page powered by CentOS Testing 123..
...
Promoting Apache and CentOS

คลาสหลัก

  • HttpClient - สร้างและส่ง request (immutable, thread-safe)
  • HttpRequest - สร้าง request (builder pattern)
  • HttpResponse - เก็บ response (status code, headers, body)

หมายเหตุ: ใน Java 11+ HttpClient ย้ายมาเป็น standard API ใน package java.net.http ไม่ต้องใช้ --add-modules แล้ว