现在 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);
}

      结果:

HttpClient加强方法 JDK11

相关文章:

  • 2021-11-29
  • 2021-04-06
  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
  • 2022-01-24
  • 2021-07-30
  • 2022-12-23
猜你喜欢
  • 2022-02-08
  • 2021-08-31
  • 2022-01-25
  • 2021-06-03
  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
相关资源
相似解决方案