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 { private static RestTemplate restTemplate; @Autowired public HttpUtil(RestTemplate restTemplate) { this.restTemplate = restTemplate; } /** * Http 通用请求封装 * * @param url 请求地址 * @param requestDto 请求实体 * @param responseClazz 返回实体Class * @param * @param * @return */ public static FxqResponseDTO execute(String url, T requestDto, Class responseClazz) { ResponseEntity 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); } }