重写http请求

@Component
@Configuration
public class CISCORestTemplate {
  
  
  private static final Logger log = LoggerFactory.getLogger(CISCORestTemplate.class);

  
  private int status;

  @Bean
  public RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
    return restTemplate;
  }

  @Bean
  public ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory =
        new HttpComponentsClientHttpRequestFactory(getHttpClient());
    factory.setConnectionRequestTimeout(3000);
    factory.setConnectTimeout(5000);
    return factory;
  }

  @Bean
  public HttpClient getHttpClient() {
    try {
      // 在调用SSL之前需要重写验证方法,取消检测SSL
      X509TrustManager trustManager = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
          return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] xcs, String str) {}

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String str) {}
      };
      SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
      ctx.init(null, new TrustManager[] {trustManager}, null);
      SSLConnectionSocketFactory socketFactory =
          new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
      // 创建Registry
      RequestConfig requestConfig = RequestConfig.custom()
          .setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(Boolean.TRUE)
          .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
          .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
      Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
          .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
          .register("https", socketFactory).build();
      // 创建ConnectionManager,添加Connection配置信息
      PoolingHttpClientConnectionManager connectionManager =
          new PoolingHttpClientConnectionManager(socketFactoryRegistry);
      final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {

        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
          return 5 * 1000;// 设置链接最大存活时间
        }
      };
      CloseableHttpClient closeableHttpClient =
          HttpClients.custom().setConnectionManager(connectionManager)
              .setDefaultRequestConfig(requestConfig).setKeepAliveStrategy(myStrategy).build();
      return closeableHttpClient;
    } catch (KeyManagementException ex) {
      throw new RuntimeException(ex);
    } catch (NoSuchAlgorithmException ex) {
      throw new RuntimeException(ex);
    }
  }

  public <T> T doPost(String uri, Object requstBody, Map<String, String> headers,
      List<String> cookies, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    // 设置header
    httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
    if (!CollectionUtils.isEmpty(headers)) {
      headers.forEach((k, v) -> {
        httpHeaders.put(k, Arrays.asList(v));
      });
    }

    if (!CollectionUtils.isEmpty(cookies)) {
      httpHeaders.put(HttpHeaders.COOKIE, cookies);
    }

    ObjectMapper o = new ObjectMapper();
    String json = "";
    try {
      json = o.writeValueAsString(requstBody);
    } catch (JsonProcessingException e1) {
      e1.printStackTrace();
    }
    RestTemplate restTemplate = getRestTemplate();
    HttpEntity<String> request = new HttpEntity<String>(json, httpHeaders); // 组装
    T rsp;
    try {
      ResponseEntity<T> response = restTemplate.exchange(uri, HttpMethod.POST, request, clazz);
      this.status = response.getStatusCodeValue();
      rsp = response.getBody();
      if (status != HttpStatus.OK.value()) {
        throw new BizException(uri + "post请求失败,返回结果:" + status);
      }
    } catch (Exception e) {
      log.info(request.getBody().toString());
      throw new BizException(
          "Execute [" + HttpMethod.POST + "] request [" + uri + "] failed due to: " + e);
    }
    return rsp;
  }

  public <T> T doGet(String uri, Map<String, String> params, Map<String, String> headers,
      List<String> cookies, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    // 设置header
    if (!CollectionUtils.isEmpty(headers)) {
      headers.forEach((k, v) -> {
        httpHeaders.put(k, Arrays.asList(v));
      });
    }

    if (!CollectionUtils.isEmpty(cookies)) {
      httpHeaders.put(HttpHeaders.COOKIE, cookies);
    }
    if(CollectionUtils.isEmpty(params)){
      params = new LinkedHashMap<String, String>();
    }
    RestTemplate restTemplate = getRestTemplate();
    HttpEntity<String> request = new HttpEntity<String>(null, httpHeaders); // 组装
    T rsp;
    try {
      ResponseEntity<T> response = restTemplate.exchange(uri, HttpMethod.GET, request, clazz, params);
      this.status = response.getStatusCodeValue();
      rsp = response.getBody();
      if (status != HttpStatus.OK.value()) {
        throw new BizException(uri + "get请求失败,返回结果:" + status);
      }
    } catch (Exception e) {
      throw new BizException(
          "Execute [" + HttpMethod.GET + "] request [" + uri + "] failed due to: " + e);
    }
    return rsp;
  }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值