Java9开始引入的一个处理 HTTP 请求的的 HTTP Client API,该 API 支持同步和异步,而在 Java 11 中已经为正式可用状态,你可以在 java.net 包中找到这个 API。
为了方便测试,我这边启动了一个服务器,访问:http://localhost:8882/find
即可返回一段json字符串。
下面来看一下HTTP Client的用法:
// 创建一个客户端,因为其构造方法受保护,所以使用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}
上面的代码是同步的,那异步的代码如下:
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());