工具类实现
@Component
public class RestTemplateUtil {
private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class);
@Resource
private UnimisConfig unimisConfig;
// 参见RestTemplate配置
@Resource(name = "restTemplate")
private RestTemplate restTemplate;
/**
* @param responseBodyType 返回体类型
* @param requestBody 请求体
* @return {@link T }
* @Description post请求
* @author wangwenying
* @date 2023-09-22
*/
public <T, A> T doPost(Class<T> responseBodyType, A requestBody, UnimisReqEnum reqType) {
try {
//请求添加token头
HttpHeaders headers = new HttpHeaders();
headers.add(UnimisConstants.APP_ID, unimisConfig.getAppId());
headers.add(UnimisConstants.APP_SECRET, unimisConfig.getAppSecret());
MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), StandardCharsets.UTF_8);
// 请求体
headers.setContentType(mediaType);
HttpEntity<A> requestEntity = new HttpEntity<>(requestBody, headers);
String url = unimisConfig.obtainRequestUrl(reqType);
logger.info("url:{} HttpEntity:{}", url, JacksonUtils.toJson(requestEntity));
ResponseEntity<T> resEntity = restTemplate.exchange(unimisConfig.obtainRequestUrl(reqType), HttpMethod.POST, requestEntity, responseBodyType);
logger.info("resEntity:{}", JacksonUtils.toJson(resEntity));
//请求结果
HttpStatus statusCode = resEntity.getStatusCode();
if (statusCode == HttpStatus.OK) {
Optional<T> body = Optional.ofNullable(resEntity.getBody());
if (body.isPresent()) {
return body.get();
}
}
} catch (Exception e) {
logger.error("Class: RestTemplateUtil; method: doPost; params:{}", JacksonUtils.toJson(responseBodyType, requestBody), e);
return null;
}
return null;
}
/**
* @param responseBodyType 返回类型
* @param requestBody 请求体
* @param uri 请求地址
* @return {@link T }
* @Description get请求
* @author wangwenying
* @date 2023-10-11
*/
public <T, A> T doGet(Class<T> responseBodyType, A requestBody, URI uri, MediaType mediaType) {
try {
logger.info("uri:{}", uri);
//请求添加token头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
HttpEntity<A> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<T> resEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, responseBodyType);
logger.info("resEntity:{}", resEntity);
//请求结果
HttpStatus statusCode = resEntity.getStatusCode();
if (statusCode == HttpStatus.OK) {
Optional<T> body = Optional.ofNullable(resEntity.getBody());
if (body.isPresent()) {
return body.get();
}
}
} catch (Exception e) {
logger.error("Class: RestTemplateUtil; method: doGet; uri:{}", uri, e);
return null;
}
return null;
}
}
标签:return,实现,RestTemplate,requestBody,headers,responseBodyType,resEntity,工具,logger
From: https://www.cnblogs.com/stubborn-dude/p/17756848.html