59 lines
2.2 KiB
Java
59 lines
2.2 KiB
Java
|
|
package com.newyetai.sdk.fangxinqian.util;
|
||
|
|
|
||
|
|
import com.newyetai.common.util.JsonUtils;
|
||
|
|
import com.newyetai.sdk.fangxinqian.dto.FxqResponseDTO;
|
||
|
|
import lombok.extern.slf4j.Slf4j;
|
||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
||
|
|
import org.springframework.http.HttpEntity;
|
||
|
|
import org.springframework.http.HttpHeaders;
|
||
|
|
import org.springframework.http.MediaType;
|
||
|
|
import org.springframework.http.ResponseEntity;
|
||
|
|
import org.springframework.stereotype.Component;
|
||
|
|
import org.springframework.util.StopWatch;
|
||
|
|
import org.springframework.web.client.RestTemplate;
|
||
|
|
|
||
|
|
@Slf4j
|
||
|
|
@Component
|
||
|
|
public class HttpUtil<T, R> {
|
||
|
|
|
||
|
|
private static RestTemplate restTemplate;
|
||
|
|
|
||
|
|
@Autowired
|
||
|
|
public HttpUtil(RestTemplate restTemplate) {
|
||
|
|
this.restTemplate = restTemplate;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Http 通用请求封装
|
||
|
|
*
|
||
|
|
* @param url 请求地址
|
||
|
|
* @param requestDto 请求实体
|
||
|
|
* @param responseClazz 返回实体Class
|
||
|
|
* @param <T>
|
||
|
|
* @param <R>
|
||
|
|
* @return
|
||
|
|
*/
|
||
|
|
public static <T, R extends FxqResponseDTO> FxqResponseDTO execute(String url, T requestDto, Class<R> responseClazz) {
|
||
|
|
ResponseEntity<R> response;
|
||
|
|
StopWatch stopWatch = new StopWatch();
|
||
|
|
stopWatch.start();
|
||
|
|
try {
|
||
|
|
log.debug("fangxinqian request url :{}", url);
|
||
|
|
log.info("fangxinqian request requestDto :{}", JsonUtils.toJsonString(requestDto));
|
||
|
|
HttpHeaders headers = new HttpHeaders();
|
||
|
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||
|
|
HttpEntity request = new HttpEntity<>(requestDto, headers);
|
||
|
|
response = restTemplate.postForEntity(url, request, responseClazz);
|
||
|
|
log.info("fangxinqian {}:{}", responseClazz.getName(), JsonUtils.toJsonString(response));
|
||
|
|
} catch (Exception e) {
|
||
|
|
log.error("fangxinqian {} invoke error:{}", requestDto.getClass().getName(),
|
||
|
|
e);
|
||
|
|
stopWatch.stop();
|
||
|
|
return FxqResponseDTO.buildCommonError();
|
||
|
|
}
|
||
|
|
stopWatch.stop();
|
||
|
|
log.info("fangxinqian consuming {} s", stopWatch.getTotalTimeSeconds());
|
||
|
|
return JsonUtils.objToClassObj(response.getBody(), responseClazz);
|
||
|
|
}
|
||
|
|
}
|