废话少说 直接上代码
package com.huaze.common.util;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.huaze.common.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import java.util.Map;
/**
* @description:http工具类
* @author: 夏士阳
* @create: 2023-07-06 10:39
**/
@Slf4j
public class HttpClientTool {
public static R get(String url, Map<String, Object> formMap) {
return createRequest(Method.GET, url, "", formMap, null);
}
public static R postBody(String url, String body ) {
return postBody( url, body, null);
}
public static R postBody(String url, String body, Map<String, String> headMap) {
return createRequest(Method.POST, url, body, null, headMap);
}
public static R postForm(String url, Map<String, Object> formMap) {
return createRequest(Method.POST, url, "", formMap, null);
}
public static R postForm(String url, Map<String, Object> formMap, Map<String, String> headMap) {
return createRequest(Method.POST, url, "", formMap, headMap);
}
public static R createRequest(Method method, String url, String body, Map<String, Object> formMap, Map<String,
String> headMap) {
try {
log.info("请求地址:{}\nbody参数:{}\nformMap参数:{}\nheadMap参数:{}", url, body, formMap, headMap);
HttpRequest request = HttpUtil.createRequest(method, url);
HttpHeaders headers = new HttpHeaders();
//追加请求headers 参数
if (MapUtil.isNotEmpty(headMap)) {
headMap.forEach((k, v) -> {
headers.set(k, v);
});
request.header(headers);
}
//访问链接 传输数据设置 10 秒超时
request.setConnectionTimeout(1000 * 10);
request.setReadTimeout(1000 * 30);
//请求方式
if (StrUtil.isNotBlank(body)) {
request.body(body);
}
if (MapUtil.isNotEmpty(formMap)) {
request.form(formMap);
}
//发送请求
HttpResponse response = request.execute();
int status = response.getStatus();
String data = response.body();
//访问是否成功
log.info("状态码:{},返回信息:{}", status, data);
if (R.SUCCESS == status) {
return R.ok(data);
} else {
return R.fail(data, "访问接口错误:"+status);
}
} catch (Exception e) {
log.error(String.format("调用接口异常:%s",e.getMessage()), e);
return R.fail();
}
}
}