Java11新特性 - 標準Java異步HTTP客戶端

Java9開始引入的一個處理 HTTP 請求的的 HTTP Client API,該 API 支持同步和異步,而在 Java 11 中已經爲正式可用狀態,你能夠在 java.net 包中找到這個 API。
爲了方便測試,我這邊啓動了一個服務器,訪問:http://localhost:8882/find便可返回一段json字符串。
下面來看一下HTTP Client的用法:java

// 建立一個客戶端,由於其構造方法受保護,因此使用HttpClient.newHttpClient靜態方法建立
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8882/find")).build();
HttpResponse.BodyHandler<String> bodyHandler = HttpResponse.BodyHandlers.ofString();
HttpResponse httpResponse = httpClient.send(request, bodyHandler);
System.out.println(httpResponse.body());

返回結果:
{"id":1,"typeId":0,"valueId":1152101,"content":"MTE=","addTime":1504933578,"status":0,"userId":15}json

上面的代碼是同步的,那異步的代碼以下:服務器

HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8882/find")).build();
HttpResponse.BodyHandler<String> bodyHandler = HttpResponse.BodyHandlers.ofString();
CompletableFuture<HttpResponse<String>> sendAsync = httpClient.sendAsync(request, bodyHandler);
HttpResponse<String> response = sendAsync.get();
System.out.println(response.body());
相關文章
相關標籤/搜索