zoukankan      html  css  js  c++  java
  • Java11新特性

    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());
    
  • 相关阅读:
    深入理解Linux修改hostname
    Linux开发环境必备十大开发工具
    管理员必备的几个Linux系统监控工具
    Solaris&&QNX® Neutrino®&&OpenVMS&&FreeBSD&&AIX
    ansible来了
    Cobbler系统安装备用链接
    Web安全
    在Eclipse/STS中使用EclEmma进行覆盖率检查
    C#中使用扩展方法
    Winform中Textbox的使用
  • 原文地址:https://www.cnblogs.com/fx-blog/p/11772817.html
Copyright © 2011-2022 走看看