SSLContext 去除证书验证


    private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
    private static final String APPLICATION_JSON = "application/json";

    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    private static final String CONTENT_TYPE_TEXT_XML = "text/xml";

    private static final String APPLICATION_XML = "application/xml";




public static String  doGetString(String url,  String charSet) throws Exception  {
		String result = "";
             HttpGet httpGet = new HttpGet(url);

		//此处跳过证书验证的方式适用于apache httpclient 4.3.x版本,并不一定适用于其他httpclient版本,请注意。
		SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(null, new TrustStrategy() {
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				//信任所有
				return true;
			}
		}).build();
		
		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
        
		Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("https", sslConnectionSocketFactory)
				.build();

		//设置连接池,配置过期时间为20s。
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
		cm.setMaxTotal(500);
		cm.setDefaultMaxPerRoute(350);

		SocketConfig socketConfig = SocketConfig.custom()
				.setSoKeepAlive(true)
				.setTcpNoDelay(true)
				.setSoTimeout(20000)
				.build();
		cm.setDefaultSocketConfig(socketConfig);

		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000).setConnectTimeout(20000).setSocketTimeout(20000).build();

		//创建httpClient
		CloseableHttpClient httpclient= HttpClients.custom()
				.setConnectionManager(cm)
				.setDefaultRequestConfig(requestConfig)
				.build(); 	
		try {
			// 使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。
			HttpResponse httpResponse = httpclient.execute(httpGet);// 其中HttpGet是HttpUriRequst的子类
			if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				httpGet.abort();
				httpclient.close();
				return result;
			}
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity,charSet);// 取出应答字符串
			// 一般来说都要删除多余的字符
			result.replaceAll("\r", "");// 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (IOException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		}finally{
			// 关闭连接,释放资源    
			try {  
				httpclient.close();  
			} catch (IOException e) {  
				e.printStackTrace();  
				result = e.getMessage().toString();
			} 
		}
		return result;
	}

    public static JSONObject doPOST(String requestUrl,
            String charSet) throws Exception {
        JSONObject jsonObject = null;

        HttpPost httpPost = new HttpPost(requestUrl);

        //此处跳过证书验证的方式适用于apache httpclient 4.3.x版本,并不一定适用于其他httpclient版本,请注意。
        SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                //信任所有
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .build();

        //设置连接池,配置过期时间为20s。
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
        cm.setMaxTotal(500);
        cm.setDefaultMaxPerRoute(350);

        SocketConfig socketConfig = SocketConfig.custom()
                .setSoKeepAlive(true)
                .setTcpNoDelay(true)
                .setSoTimeout(20000)
                .build();
        cm.setDefaultSocketConfig(socketConfig);

        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000).setConnectTimeout(20000).setSocketTimeout(20000).build();

        //创建httpClient
        CloseableHttpClient httpclient= HttpClients.custom()
                .setConnectionManager(cm)
                .setDefaultRequestConfig(requestConfig)
                .build();     

        try {
            // 使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。
            HttpResponse httpResponse = httpclient.execute(httpPost);// 其中HttpGet是HttpUriRequst的子类

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                httpPost.abort();
                httpclient.close();
                jsonObject = JSONObject.fromObject(result);

                return jsonObject;
            }

            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity,charSet);// 取出应答字符串
            // 一般来说都要删除多余的字符

            result.replaceAll("\r", "");// 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            result = e.getMessage().toString();
        } catch (IOException e) {
            e.printStackTrace();
            result = e.getMessage().toString();
        }finally{
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
                result = e.getMessage().toString();
            } 
        }

        jsonObject = JSONObject.fromObject(result);
        return jsonObject;    

    }
 

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值