All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.arextest.storage.client.HttpWebServiceApiClient Maven / Gradle / Ivy

There is a newer version: 1.3.4
Show newest version
package com.arextest.storage.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author jmo
 * @since 2021/9/15
 */
@Component
@Slf4j
@SuppressWarnings({"java:S1192", "java:S1123", "java:S119", "java:S1181"})
public final class HttpWebServiceApiClient {

  private final static int TEN_SECONDS_TIMEOUT = 10_000;
  private RestTemplate restTemplate;
  @Resource
  private ObjectMapper objectMapper;

  @Autowired(required = false)
  private List clientHttpRequestInterceptors;

  @PostConstruct
  private void initRestTemplate() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setConnectTimeout(TEN_SECONDS_TIMEOUT);
    requestFactory.setReadTimeout(TEN_SECONDS_TIMEOUT);
    final int initialCapacity = 10;
    List> httpMessageConverterList = new ArrayList<>(initialCapacity);
    httpMessageConverterList.add(new ByteArrayHttpMessageConverter());
    httpMessageConverterList.add(new StringHttpMessageConverter());
    httpMessageConverterList.add(new ResourceHttpMessageConverter());
    httpMessageConverterList.add(new SourceHttpMessageConverter<>());
    httpMessageConverterList.add(new AllEncompassingFormHttpMessageConverter());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(
        objectMapper);
    converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
    httpMessageConverterList.add(converter);
    this.restTemplate = new RestTemplate(httpMessageConverterList);
    this.restTemplate.setRequestFactory(requestFactory);
    if (!CollectionUtils.isEmpty(clientHttpRequestInterceptors)) {
      this.restTemplate.setInterceptors(clientHttpRequestInterceptors);
    }
  }

  public  TResponse get(String url, Map urlVariables,
      Class responseType) {
    try {
      return restTemplate.getForObject(url, responseType, urlVariables);
    } catch (Throwable throwable) {
      LOGGER.error("http get url: {} ,error: {} , urlVariables: {}", url, throwable.getMessage(),
          urlVariables,
          throwable);
    }
    return null;
  }

  public  ResponseEntity get(boolean inner, String url,
      Map urlVariables,
      ParameterizedTypeReference responseType) {
    try {
      return restTemplate.exchange(url, HttpMethod.GET, null, responseType, urlVariables);
    } catch (Throwable throwable) {
      LOGGER.error("http get url: {} ,error: {} , urlVariables: {}", url, throwable.getMessage(),
          urlVariables,
          throwable);
    }
    return null;
  }

  public  TResponse get(String url, Map urlVariables,
      MultiValueMap headers, Class responseType) {
    try {
      HttpEntity request = new HttpEntity<>(headers);
      return restTemplate.exchange(url, HttpMethod.GET, request, responseType, urlVariables)
          .getBody();
    } catch (Throwable throwable) {
      LOGGER.error("http get url: {} ,error: {} , urlVariables: {} ,headers: {}", url,
          throwable.getMessage(),
          urlVariables, headers,
          throwable);
    }
    return null;
  }

  public  TResponse jsonPost(String url, TRequest request,
      Class responseType) {
    try {
      return restTemplate.postForObject(url, wrapJsonContentType(request), responseType);
    } catch (Throwable throwable) {
      try {
        LOGGER.error("http post url: {} ,error: {} ,request: {}", url, throwable.getMessage(),
            objectMapper.writeValueAsString(request), throwable);
      } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }
    return null;
  }

  public  ResponseEntity responsePost(String url,
      TRequest request,
      Class responseType, HttpHeaders headerValue) {
    try {
      return restTemplate.postForEntity(url, wrapJsonContentTypeWithHeader(request, headerValue),
          responseType);
    } catch (Throwable throwable) {
      try {
        LOGGER.error("http post url: {} ,error: {} ,request: {}", url, throwable.getMessage(),
            objectMapper.writeValueAsString(request), throwable);
      } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }
    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
  }

  @SuppressWarnings("unchecked")
  private  HttpEntity wrapJsonContentType(TRequest request) {
    HttpEntity httpJsonEntity;
    if (request instanceof HttpEntity) {
      httpJsonEntity = (HttpEntity) request;
    } else {
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
      httpJsonEntity = new HttpEntity<>(request, headers);
    }
    return httpJsonEntity;
  }

  private  HttpEntity wrapJsonContentTypeWithHeader(TRequest request,
      HttpHeaders headerValue) {
    HttpEntity httpJsonEntity;
    if (request instanceof HttpEntity) {
      httpJsonEntity = (HttpEntity) request;
    } else {
      httpJsonEntity = new HttpEntity<>(request, headerValue);
    }
    return httpJsonEntity;
  }

  public  ResponseEntity exchange(String url,
      HttpMethod method,
      HttpEntity requestEntity,
      Class responseType) throws RestClientException {
    return restTemplate.exchange(url, method, requestEntity, responseType);
  }

  public  ResponseEntity jsonPostWithThrow(String url,
      HttpEntity request,
      Class responseType) throws RestClientException {
    return restTemplate.postForEntity(url, wrapJsonContentType(request), responseType);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy