InsCrawlerOrderComponents.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.ydtech.modules.order.components;
  2. import com.alibaba.fastjson.JSON;
  3. import com.ydtech.constants.InsuranceEnum;
  4. import com.ydtech.exception.SystemException;
  5. import com.ydtech.modules.order.utils.InsuranceLog;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.http.HttpEntity;
  8. import org.springframework.http.HttpHeaders;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.lang.Nullable;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.web.client.RestTemplate;
  14. @Slf4j
  15. @Component
  16. public class InsCrawlerOrderComponents {
  17. private final RestTemplate restTemplate;
  18. public InsCrawlerOrderComponents(RestTemplate restTemplate) {
  19. this.restTemplate = restTemplate;
  20. }
  21. public <T, B> B post(String url, String logId, String message, @Nullable T requestBody, Class<B> responseType, HttpHeaders httpHeaders) {
  22. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  23. HttpEntity<T> yaQuoteInfoVoHttpEntity = new HttpEntity<>(requestBody, httpHeaders);
  24. String request = JSON.toJSONString(requestBody);
  25. InsuranceLog.infoLog(logId, "\n\t---------> {} \n\t---------> URL: {} \n\t---------> 请求参数: {}", message, url, request);
  26. ResponseEntity<B> stringResponseEntity = restTemplate.postForEntity(url, yaQuoteInfoVoHttpEntity, responseType);
  27. B body = stringResponseEntity.getBody();
  28. if (body == null) {
  29. throw new SystemException(message + "接口请求失败");
  30. }
  31. String response = JSON.toJSONString(body);
  32. InsuranceLog.infoLog(logId, "\n\t---------> {} \n\t---------> 响应参数:{}", message, response);
  33. return body;
  34. }
  35. public <T, B> B request(String url, String companyId, String apiType, T requestBody, Class<B> responseType) {
  36. // 获取保险公司枚举
  37. String substring = companyId.substring(0, 4);
  38. InsuranceEnum insuranceEnum = Enum.valueOf(InsuranceEnum.class, substring);
  39. return this.request(url, insuranceEnum, apiType, requestBody, responseType, new HttpHeaders());
  40. }
  41. public <T, B> B request(String url, InsuranceEnum insuranceEnum, String apiType, T requestBody, Class<B> responseType) {
  42. return this.request(url, insuranceEnum, apiType, requestBody, responseType, new HttpHeaders());
  43. }
  44. public <T, B> B request(String url, InsuranceEnum insuranceEnum, String apiType, T requestBody, Class<B> responseType, HttpHeaders httpHeaders) {
  45. String message = insuranceEnum.getName() + apiType;
  46. return this.post(url, insuranceEnum.getPinyin(), message, requestBody, responseType, httpHeaders);
  47. }
  48. }