#记录一下工作中遇到的小问题#
HttpPost method = new HttpPost(url);
BasicCookieStore store = new BasicCookieStore();
HttpClient httpClient = null;
String result = null;
long requestTime = 0L;
//https 请求忽略证书
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", sslConnectionSocketFactory).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(100);
httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(cm).setDefaultCookieStore(store).build();
} catch (NoSuchAlgorithmException e) {
logger.error("https忽略SSL证书错误 错误信息:"+e.getMessage(),e);
throw new RuntimeException(e);
} catch (KeyStoreException e) {
logger.error("https忽略SSL证书错误 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
throw new RuntimeException(e);
} catch (KeyManagementException e) {
logger.error("https忽略SSL证书错误 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
throw new RuntimeException(e);
}
if (method != null) {
try {
// 建立一个NameValuePair数组,用于存储欲传送的参数
method.addHeader("Content-type",
"application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
method.setHeader("Connection", "close");
long start = System.currentTimeMillis();
HttpResponse response = httpClient.execute(method);
requestTime = System.currentTimeMillis() - start;
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.error("http请求失败:url=" + url + "----response=" + response.getStatusLine());
} else {
result = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.info("URL = "+url+ " 返回结果 = ");
logger.error("https请求错误! 错误信息:"+e.getMessage()+" 请求Url="+url ,e);
} finally {
if (method != null) {
try {
method.releaseConnection();
// 关闭连接
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
} catch (Exception re) {
logger.error(re.getMessage(),re);
}
}
}
}
logger.info("https请求成功! 耗时={}ms Url={} return={}",requestTime, url, result);
logger.info("URL = "+url+ " 返回结果 = "+result);
return result;