http库 之 OKHttpUtil

源码位置

方便实用,个人感觉不错

依赖

xml 复制代码
<dependency>
    <groupId>io.github.admin4j</groupId>
    <artifactId>common-http-starter</artifactId>
    <version>0.7.5</version>
</dependency>

代码实践

java 复制代码
/**
 * 通用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;
}

以上只是我写的一个测试函数,具体使用还是要看一下源码.

相关推荐
Remember_99314 小时前
一文吃透Java WebSocket:原理、实现与核心特性解析
java·开发语言·网络·websocket·网络协议·http·p2p
古译汉书2 天前
【IoT死磕系列】Day 3:学习HTTP!实战:STM32手写GET请求获取天气实战(附源码+八股文)
数据结构·stm32·物联网·网络协议·学习·算法·http
南部余额2 天前
Spring Boot ResponseEntity响应处理与文件下载实战
spring boot·后端·http
Starry_hello world3 天前
Linux http代码
linux·运维·http
九狼3 天前
Flutter SSE 流式响用 Dio 实现 OpenAI 兼容接口的逐 Token 输出
http·设计模式·api
nix.gnehc3 天前
在K8s集群中部署Traefik并验证Python HTTP服务
python·http·kubernetes
执行部之龙3 天前
HTTP常见面试题总结
网络·网络协议·http
猫头虎4 天前
web开发常见问题解决方案大全:502/503 Bad Gateway/Connection reset/504 timed out/400 Bad Request/401 Unauthorized
运维·前端·nginx·http·https·gateway·openresty
无籽西瓜a4 天前
SSL/TLS工作流程以及HTTP与HTTPS详解
http·https·ssl