在 Java 中請求 HTTP 客戶端並獲取響應
我們將使用 Java 中的 HTTP 客戶端來傳送請求和接收響應。同時,你還將學習如何使用主體處理程式、構建器和其他底層方法來傳送 HTTP 客戶端請求。
在 Java 中傳送 HTTP 請求並從客戶端接收 JSON 響應
我們將使用程式設計師用來評估其 HTTP 請求的演示 JSON 網站。這裡是 https://blog.typicode.com/
。
在此之前,請記下以下對你有幫助的方法。
HttpClient send2client = HttpClient.newHttpClient();
- 我們使用它向客戶端傳送 http 請求並接收響應。HttpRequest Req2client = HttpRequest();
- 此方法有助於將 http 請求構建為具有以下引數的例項。
2.1.newBuilder();
- 生成一個 Http 請求構建器。此方法返回一個構建標準 HTTP 客戶端 API 物件的構建器。
2.2.uri("客戶端 URL");
- 設定 http 請求的 URL。
2.3.build();
- 該引數構建並返回 http 請求。HttpResponse<String> clientRes = send2client.send(Req2client, HttpResponse.BodyHandlers.ofString());
- 響應狀態碼、響應頭、響應體,以及該響應對應的 HTTP Request 都可以通過這個類訪問。
檢視以下程式,它執行我們到目前為止討論的所有內容。
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Example1 {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient send2client = HttpClient.newHttpClient();
HttpRequest Req2client = HttpRequest.newBuilder().uri(URI.create("https://blog.typicode.com/")).build();
String format = System.getProperty("line.separator");
HttpResponse<String> clientRes = send2client.send(Req2client, HttpResponse.BodyHandlers.ofString());
System.out.println(" Requested Responses from the client" + format + "1: Status code" + format+ clientRes.statusCode() + format);
System.out.println("2: Uniform Resource Locator (URL) from the client" + clientRes.uri() + format);
System.out.println("3: SSL Session" + format + clientRes.sslSession() + format);
System.out.println("4: HTTP version" + format + clientRes.version() + format);
//System.out.println("5: Response Header" + format + clientRes.headers() + format);
//System.out.println("6: Response Body" + format + clientRes.body() + format);
}
}
輸出:
Requested Responses from the client
1: Status code
200
2: Uniform Resource Locator (URL) from the client: https://blog.typicode.com/
3: SSL Session
Optional[jdk.internal.net.http.common.ImmutableExtendedSSLSession@5bcea91b]
4: HTTP version
HTTP_2
在 Java 中非同步執行 HTTP 請求並獲取響應
我們將在以下程式碼塊中使用相同的 HttpRequest
方法,但具有以下功能。
sendAsync()
- 此客戶端使用指定的響應正文處理程式非同步傳送指定的請求。
sendAsync()
和 HttpRequest
是傳送和檢索方法。兩者對於 HTTP Web 處理程式都是安全的。
語法:
Cli.sendAsync(RQI, BodyHandlers.ofString())
.thenApply(HttpResponse::body) //optional
.thenAccept(System.out::println) //The action to take before completing the retrieved completion stage
.join(); //returts the response value
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
public class Example2 {
public static void main(String[] args) {
HttpClient Cli = HttpClient.newHttpClient();
HttpRequest RQI = HttpRequest.newBuilder()
.uri(URI.create("https://www.delftstack.com"))
.build();
Cli.sendAsync(RQI, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
}
輸出:
Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.
LinkedIn