import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* JDK version: 1.8
*
* @Author : lah
* @create 2023/6/27 11:24
* Description: No Description
*/
@Component
@Slf4j
public class HttpUtil {
/**
* 发送携带请求头的请求
*
* @param type Http方法枚举
* @param body 携带body
* @param url 请求路径
* @param headers 请求头
* @param isOverrideHeaders 是否覆盖请求头
* @return json字符串
*/
public static JSONObject request(Method type, String body, String url, Map<String, String> headers, boolean isOverrideHeaders) {
log.info("url:{}", url);
log.info("method:{}", type);
String result = cn.hutool.http.HttpUtil.createRequest(type, url).headerMap(headers, isOverrideHeaders)
.body(body)
.execute().body();
if (ObjectUtil.isEmpty(result)) {
throw new RuntimeException("网络异常");
}
return JSON.parseObject(result);
}
/**
* 发送不携带请求头的请求
* @param type Http方法枚举
* @param body 携带body
* @param url 请求路径
* @return 返回的json对象
*/
public static JSONObject request(Method type, String body, String url) {
log.info("url:{}", url);
log.info("method:{}", type);
String result = cn.hutool.http.HttpUtil.createRequest(type, url)
.body(body)
.execute().body();
if (ObjectUtil.isEmpty(result)) {
throw new RuntimeException("网络异常");
}
return JSON.parseObject(result);
}```
基于hutool的http通讯工具类
最新推荐文章于 2024-05-28 10:31:16 发布