课余时间,阅读别人和自己的总结常用的RestTemplateUtils 调用
package com.app.common.utils.http;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.app.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Component
public class RestTemplateUtils {
@Resource
private RestTemplate restTemplate;
private static RestTemplateUtils httpUtil;
/**
* 1.初始化的时候:进行赋值到一个定义的静态变量。
* 2.静态变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入。
* 所以我们不能@resource一个静态变量,使之成为一个spring bean。但是静态方法又不能调用非静态的属性。
* 所以要维护一个工具类的静态实例,初始化的时候把restTemplate传进来,这样就可以直接调用HttpUtil.xx()方法。
*/
@PostConstruct
public void init(){
httpUtil = this;
httpUtil.restTemplate = this.restTemplate;
}
/**
* post请求JSON
* @param apiDesc :接口描述
* @param apiUrl:接口链接
* @param reqParam :请求参数
* @return 返回JSON数据
*/
public static JSONObject postJson(String apiDesc,String apiUrl, Map<String,Object> reqParam) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String,Object>> requestEntity = new HttpEntity<>(reqParam,headers);
ResponseEntity<JSONObject> responseEntity = post(apiDesc, apiUrl, requestEntity);
return responseEntity.getBody();
} catch (Exception e) {
log.error("第三方接口异常", e);
throw new ServiceException("请求接口异常:" + e.getMessage());
}
}
/**
* post请求 form
* @param apiDesc :接口描述
* @param apiUrl:接口链接
* @param reqParam :请求参数
* @return 返回JSON数据
*/
public static JSONObject postForm(String apiDesc,String apiUrl, Map<String,Object> reqParam) {
try {
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
reqParam.forEach(postParameters::add);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(postParameters,headers);
ResponseEntity<JSONObject> responseEntity = post(apiDesc, apiUrl, requestEntity);
return responseEntity.getBody();
} catch (Exception e) {
log.error("第三方接口异常", e);
throw new ServiceException("请求接口异常:" + e.getMessage());
}
}
/**
* post请求 form 文件
* @param apiDesc :接口描述
* @param apiUrl:接口链接
* @param reqParam :请求参数
* @return 返回JSON数据
*/
public static JSONObject postFile(String apiDesc,String apiUrl, Map<String,Object> reqParam) {
try {
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
reqParam.forEach(postParameters::add);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(postParameters,headers);
ResponseEntity<JSONObject> responseEntity = post(apiDesc, apiUrl, requestEntity);
return responseEntity.getBody();
} catch (Exception e) {
log.error("第三方接口异常", e);
throw new ServiceException("请求接口异常:" + e.getMessage());
}
}
/**
* post 请求
* @param apiDesc
* @param apiUrl
* @param requestEntity
* @return
* @param <T>
*/
@NotNull
private static <T> ResponseEntity<JSONObject> post(String apiDesc, String apiUrl, HttpEntity<T> requestEntity) {
log.info("请求接口:[{}],请求链接:[{}],请求数据:[{}]", apiDesc, apiUrl, JSON.toJSONString(requestEntity));
ResponseEntity<JSONObject> responseEntity = httpUtil.restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, JSONObject.class);
log.info("响应返回:[{}],请求链接:[{}],响应结果:[{}]", apiDesc, apiUrl, JSON.toJSONString(responseEntity));
if (!responseEntity.getStatusCode().is2xxSuccessful() || Objects.isNull(responseEntity.getBody())) {
throw new ServiceException("请求接口异常!");
}
return responseEntity;
}
/**
* get 请求
* @param apiDesc :接口描述
* @param apiUrl :接口链接
* @param reqParam :请求参数
* @return 返回JSON
*/
public static JSONObject get(String apiDesc,String apiUrl, Map<String,Object> reqParam) {
try {
//创建请求头
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(null, headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl);
//如果存在参数
if (!reqParam.isEmpty()) {
for (Map.Entry<String, Object> e : reqParam.entrySet()) {
//构建查询参数
builder.queryParam(e.getKey(), e.getValue());
}
apiUrl = builder.build().toString();
}
log.info("请求接口:[{}],请求链接:[{}],请求数据:[{}]", apiDesc, apiUrl, JSON.toJSONString(requestEntity));
ResponseEntity<JSONObject> responseEntity = httpUtil.restTemplate.exchange(apiUrl, HttpMethod.GET, requestEntity, JSONObject.class);
log.info("响应返回:[{}],请求链接:[{}],响应结果:[{}]", apiDesc, apiUrl, JSON.toJSONString(responseEntity));
if (!responseEntity.getStatusCode().is2xxSuccessful() || Objects.isNull(responseEntity.getBody())) {
throw new ServiceException("请求接口异常!");
}
return responseEntity.getBody();
} catch (Exception e) {
log.error("第三方接口异常", e);
throw new ServiceException("请求接口异常:" + e.getMessage());
}
}
}