数据通讯
1.报文通讯模式
采用 https 协议进行交互。通过 post 方式提交报文信息,请求参数为标准表单参数串形式。
2.实例
/**
* 调用接口
* @param url
* @param reportContent
* @param charset
* @return
*/
public static String sendHttpsPost(String url, String reportContent, String charset) throws Exception {
// 记录开始时间
long start = System.currentTimeMillis();
CloseableHttpClient closeableHttpClient = null;
CloseableHttpResponse response = null;
try {
closeableHttpClient = createSSLClientDefault();
// 请求参数设置
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(SO_TIME_OUT).build();
httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);
httpPost.setConfig(requestConfig);
// 发送请求
httpPost.setEntity(new StringEntity(reportContent, charset));
response = closeableHttpClient.execute(httpPost);
// 处理响应
StatusLine statusLine = response.getStatusLine();
String responseContent = EntityUtils.toString(response.getEntity(), charset);
if (200 == statusLine.getStatusCode()) {
logger.info("apacheHttpsClient请求成功,响应内容为:" + responseContent);
} else {
logger.info("apacheHttpsClient请求失败,响应内容为:" + responseContent);
}
long end = System.currentTimeMillis();
logger.info("apacheHttpsClient请求耗时:" + (end - start) + "毫秒");
return responseContent;
} catch (Exception e) {
logger.error("调用现在支付接口失败!错误信息:{}",e);
throw e;
} finally {
try {
if (response != null) response.close();
if (closeableHttpClient != null) closeableHttpClient.close();
} catch (Exception ex) {
logger.error("apacheHttpsClient调用--关闭流失败", ex);
}
}
}
private static CloseableHttpClient createSSLClientDefault() throws Exception {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception ex) {
logger.error("apacheHttpsClient创建CloseableHttpClient失败", ex);
throw ex;
}
}