今天看啥  ›  专栏  ›  奶盐味小圆饼

java基于java.net.http实现第三方服务的后端调用

奶盐味小圆饼  · 简书  ·  · 2020-04-09 17:02

HTTP是基于客户端/服务端(C/S)的架构模型,通过一个可靠的链接来交换信息,是一个无状态的 请求/响应 协议。
一个HTTP"客户端"是一个应用程序(Web浏览器或其他任何客户端),通过连接到服务器达到向服务器发送一个或多个HTTP的请求的目的。
一个HTTP"服务器"同样也是一个应用程序(通常是一个Web服务,如Apache Web服务器或IIS服务器等),通过接收客户端的请求并向客户端发送HTTP响应数据。
HTTP使用统一资源标识符(Uniform Resource Identifiers, URI )来传输数据和建立连接。

  • post json: body要json化为string,然后header指定是json格式
public void vehicleRecordAddJson(VehicleRecordRequest request){
        try {
        String requestBody = JsonUtil.serialize(request); 
        logger.debug("request body: {}", requestBody);
        HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(properties.getUrl() + "/blockchain/v1/vehicle/create"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        CompletableFuture<String> result = HttpClient.newHttpClient()
                .sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .exceptionally(err -> {
                    err.printStackTrace();
                    return "fallback";
                });
        CodeMessageModel model = JsonUtil.deserialize(result.get(), CodeMessageModel.class);
        logger.info(model.getMessage());
        } catch (InterruptedException | ExecutionException | IOException e) {
            e.printStackTrace();
        }
    }
  • 在对List<String> peerWithOrgs 进行初始化的时候遇到了困难,放在这里记录一下吧.
   List<String> peerWithOrgs = new ArrayList<>(){{add("peerpansen");}};
   recordRequest.setPeerWithOrgs(peerWithOrgs);
  • 这里想把配置文件的信息,读取并自动封装成实体类,可以使用@ConfigurationProperties,把配置信息自动封装成实体类使用。实体类中除了要加@ConfigurationProperties还要加上@Component才能把配置信息注入IOC容器中。
//从配置信息中搜索前缀为"blockchain"的信息,读取并自动封装成实体类
@Component
@ConfigurationProperties(prefix = "blockchain")
public class Properties {
    /**
     * 是否打开
     */
    private boolean open = false;
    /**
     * 服务地址
     */
    private String url;

    public boolean isOpen() {
        return open;
    }

    public void setOpen(boolean open) {
        this.open = open;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url == null ? null : url.trim();
    }
}
  • 基于配置文件对application.yml进行配置,对两个参数进行初始化操作
blockchain:
  open: true
  url: http://192.168.1.8:9999
  • 在对Json进行处理的过程中,对象的名称也要做到一致,@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,
@JsonProperty("english_name")
    private String englishName;
  • 序列化方法这里调用了公共方法,实现方式如下,可以看出这里还是调用了objectMapper类,把对象转化为了字符串
public static <T> String serialize(T object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }
  • 有序列化,当然也有发序列化的需求,这里
Model model = JsonUtil.deserialize(result.get(), Model.class);
  • 反序列化的实现接口
public static <T> T deserialize(String json, Class<T> clazz) throws IOException {
        return objectMapper.readValue(json, clazz);
    }



原文地址:访问原文地址
快照地址: 访问文章快照