最近项目中和外部接口交互时遇到问题,项目本身是http形式的接口协议,需要请求https的接口协议,代码中使用的是httpClient进行实现,
1、pom文件引入:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2、重写HTTPClient方法,代码块用到如下参数:
@Value("${keyStoreSim.path}") String keyStorePath; @Value("${trustStoreSim.path}") String trustStorePath; @Value("${keyStorePwd.Sim}") String keyStorePwd; @Value("${trustStorePwd.Sim:}") String trustStorePwd;
public String httpClientPost(String httpUrl, String inJson) throws Exception{
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
// .setSocketTimeout(5000).build();
// 创建post请求
/* HttpPost httpPost = new HttpPost(httpUrl);
HttpResponse response = null;
HttpEntity entity = null;
StringEntity stringEntity = new StringEntity(inJson, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
httpPost.setEntity(stringEntity);
String responseContent = null;*/
// try {
// 创建默认的httpClient实例.
// mailSimHttpClient = HttpClients.createDefault();
// httpPost.setConfig(requestConfig);
// 执行请求
/* response = getSimHttpClient().execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");*/
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// // 关闭连接,释放资源
// if (response != null) {
// response.close();
// }
// if (httpClient != null) {
// httpClient.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
HttpPost httpPost = new HttpPost(httpUrl);
//
StringEntity entiy = new StringEntity(inJson, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
httpPost.setEntity(entiy);
Long time = System.currentTimeMillis();
HttpResponse response = getSimHttpClient().execute(httpPost);
Log.outSysLog("执行httpclient所需要的时间.getSimHttpClient.execute(httpPost)" + (System.currentTimeMillis() - time) );
String responseContent ="";
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300)
{
String str = "code:"+ MessageCode.INTERFACE_ID_WRONG.code+"HTTP Request is not success, Response code is "+ response.getStatusLine().getStatusCode()+",responseContent="+EntityUtils.toString(response.getEntity(), "UTF-8");
throw new CommonsException(MessageCode.INTERFACE_ID_WRONG,str);
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
{
responseContent = EntityUtils.toString(response.getEntity(),"UTF-8");
EntityUtils.consume(response.getEntity());
}
String rsp=responseContent.toString();
return responseContent;
}
/**
* 注意:
* 这里返回的Executor是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@SuppressWarnings("deprecation")
public HttpClient getSimHttpClient() throws Exception {
Long time = System.currentTimeMillis();
HttpClient client = new DefaultHttpClient();
//CloseableHttpClient client = HttpClients.createDefault();
SSLContext ctx = SSLContext.getInstance("TLS");
System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(keyStorePath), keyStorePwd.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
kmf.init(ks, keyStorePwd.toCharArray());
KeyStore ts = KeyStore.getInstance("jks");
ts.load(new FileInputStream(trustStorePath), trustStorePwd.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
tmf.init(ts);
ctx.init(kmf.getKeyManagers(), new TrustManager[] { tm }, null);
org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(ctx);
//SSLConnectionSocketFactory sslsf =
// new SSLConnectionSocketFactory(sslcontext, null, null,
// SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
client = new DefaultHttpClient(ccm, client.getParams());
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
soketTimeOut);
Log.outSysLog("封装httpclient所需要的时间.getSimHttpClient" + (System.currentTimeMillis() - time) );
return client;
}