调用外部接口支持https请求

1,创建RestTemplateConfig.java文件,内容如下:

package com.htsec.monitor.internet.config;


import com.htsec.monitor.internet.util.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;


@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplate httpsRestTemplate(HttpComponentsClientHttpRequestFactory httpsFactory) {
RestTemplate restTemplate = new RestTemplate(httpsFactory);
restTemplate.setErrorHandler(
new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) {
return false;
}

@Override
public void handleError(ClientHttpResponse clientHttpResponse) {
// 默认处理非200的返回,会抛异常
}
});
return restTemplate;
}

@Bean(name = "httpsFactory")
public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory()
throws Exception {
CloseableHttpClient httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
HttpComponentsClientHttpRequestFactory httpsFactory =
new HttpComponentsClientHttpRequestFactory(httpClient);
httpsFactory.setReadTimeout(40000);
httpsFactory.setConnectTimeout(40000);
return httpsFactory;
}
}
2,创建HttpClientUtils.java文件,内容如下:
package com.htsec.monitor.internet.util;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpClientUtils {

public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClientBuilder b = HttpClientBuilder.create();

// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);

// don't check Hostnames, either.
// -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();

// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
connMgr.setMaxTotal(200);
connMgr.setDefaultMaxPerRoute(100);
b.setConnectionManager( connMgr);

// finally, build the HttpClient;
// -- done!
CloseableHttpClient client = b.build();

return client;
}

}
3,创建调用类接方法,EccHttpUtils.java
package com.htsec.monitor.internet.util;

import com.alibaba.fastjson.JSONObject;
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.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


/**
* Created by LQZ on 2019/11/13.
*/

@Slf4j
@Component
public class EccHttpUtils {

//支持https,这个地方注入的就是第1步中创建的@Bean,restTemplate这个单词无所谓,随意起名字

@Autowired
RestTemplate restTemplate;


public JSONObject doPost(String url,JSONObject requestBody) { //外部调用方法

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json");


/*requestBody.put("page", 1);
requestBody.put("size", 1);*/
HttpEntity<String> httpEntity = null;
if(requestBody!=null) {
httpEntity = new HttpEntity<String>(requestBody.toJSONString(), httpHeaders);
}else{
httpEntity = new HttpEntity<>(httpHeaders);
}
log.info("请求外部接口url="+url+",请求参数(允许null)="+requestBody);
JSONObject result = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JSONObject.class).getBody();
log.info("请求外部接口返回result="+result);
return result;
}
}


posted @ 2019-11-14 15:10  仔儿仔  阅读(1075)  评论(0编辑  收藏  举报