Http请求工具类

/**
 * https方法调用
 * @return
 */
public static CloseableHttpClient getHttpsClient() {
	RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
	try {
		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		// 信任任何链接
		TrustStrategy anyTrustStrategy = new TrustStrategy() {
			@Override
			public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
				// TODO Auto-generated method stub
				return true;
			}
		};
		SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
		// 防止缓存过大导致内存过大,这样设置可能会出现频繁GC,可以屏蔽这一行
		sslContext.getClientSessionContext().setSessionCacheSize(1000);
		LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2", "TLSv1.1", "SSLv3"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		registryBuilder.register("https", sslSF);
	} catch (KeyStoreException e) {
		throw new RuntimeException(e);
	} catch (KeyManagementException e) {
		throw new RuntimeException(e);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(registryBuilder.build())).build();// 构建客户端
}

调用方法

public static String getHttpsGet(String url, int connTimeout, int readTimeout) throws IOException {
	// 创建Get请求
	String body = "";
	try {
		CloseableHttpClient httpClient = getHttpsClient();
		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000*connTimeout).setConnectionRequestTimeout(1000*readTimeout).setSocketTimeout(1000*readTimeout).build();
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response = httpClient.execute(httpGet);    // 由客户端执行(发送)Get请求
		HttpEntity responseEntity = response.getEntity();    // 从响应模型中获取响应实体
		 body = EntityUtils.toString(responseEntity);
	}catch (Exception e){
		logger.error("调用异常:url{}",url,e.getMessage());
	}
	return body;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值