现在 Java 自带了这个 HTTP Client API,我们以后还有必要用 Apache 的 HttpClient 工具包吗?
4.1 需要远程调用的接口
@RequestMapping(value = "/dshjbca")
public String test1(){
return "dfs";
}
4.2 HttpClient调用该接口
//同步调用
@Test
public void test2() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("")).build();
BodyHandler<String> handler = HttpResponse.BodyHandlers.ofString();
HttpResponse<String> response = client.send(request,handler);
String body = response.body();
System.out.println(body);
}
//异步调用
@Test
public void test3() throws IOException, InterruptedException, ExecutionException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("")).build();
BodyHandler<String> handler = HttpResponse.BodyHandlers.ofString();
CompletableFuture<HttpResponse<String>> response = client.sendAsync(request,handler);
HttpResponse<String> result = response.get();
String body = result.body();
System.out.println(body);
}
结果: