http库 之 OKHttpUtil

源码位置

方便实用,个人感觉不错

依赖

<dependency>
    <groupId>io.github.admin4jgroupId>
    <artifactId>common-http-starterartifactId>
    <version>0.7.5version>
dependency>

代码实践

/**
 * 通用http的post接口,返回body的JsonNode对象
 * @param URI 资源地址
 * @param object post请求参数,requestBody
 */
private JsonNode CommonHttpRequest(String URI, Object object){
    JsonNode data = null;
    try {
    	//BaseURL为配置文件中配置的内容
        Response post = HttpUtil.post(BaseURL + URI, object);
        if (post == null || post.body() == null){
            log.error("no response, post or body is null");
            throw new Exception("no response");
        }
        //测试环境为springboot 2.x,所以使用的jackson
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(Objects.requireNonNull(post.body(), "No Response From server").string());
        log.info("response: {}", jsonNode);
        int code = jsonNode.get("code").asInt();
        if (code != 200){
            log.error("Request failed, code: [{}]", code);
            throw new Exception("server code error");
        }
        data = jsonNode.get("data");
    }catch (Exception e){
        log.error("Http process failed.", e);
        throw new BusinessException(CodeEnum.SYSTEM_EXCEPTION);
    }
    return data;
}

以上只是我写的一个测试函数,具体使用还是要看一下源码.
http库 之 OKHttpUtil_第1张图片

你可能感兴趣的:(网络传输协议,http)