MangoCool

Java HttpURLConnection添加对https信任

2018-06-04 14:59:20   作者:MangoCool   来源:MangoCool

经常用到,记录一下,直接贴代码:

package com.mangocool.https;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.log4j.Logger;

public class HttpsTrustCertDemo {
	
	private static final Logger logger = Logger.getLogger(HttpsTrustCertDemo.class);
	
	public HttpsTrustCertDemo() {
		
	}

	/**
	  * 获取url状态码
	  * @param url
	  * @return 状态码
	  */
	private int getResponseCode(String URL) {
		// 判断url是否为真实的链接
		int responseCode = 404;
		try {
			URL url = new URL(URL);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			SSLSocketFactory oldSocketFactory = null;
	        HostnameVerifier oldHostnameVerifier = null;
	        boolean useHttps = URL.startsWith("https");
	        if (useHttps) {
	            HttpsURLConnection conn = (HttpsURLConnection) connection;
	            oldSocketFactory = trustAllHosts(conn);
	            oldHostnameVerifier = conn.getHostnameVerifier();
	            conn.setHostnameVerifier(DO_NOT_VERIFY);
	            responseCode = connection.getResponseCode();
	        }
		} catch (Exception e1) {
			System.out.println("获取http请求状态码异常");
			e1.printStackTrace();
		}
		System.out.println(URL + " 该链接的状态码为:" + responseCode);
		return responseCode;
	}

	/**
	 * @param url 接口服务地址
	 * @param sendText 发送内容
	 * @return
	 * @throws Exception
	 */
	private String testConnection(String URL, String sendText) throws Exception {
		HttpsURLConnection conn = null;
		try {
			if (sendText == null || sendText.length() == 0) {
				return null;
			}
			String returnValue = null;
			URL url = new URL(URL);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			SSLSocketFactory oldSocketFactory = null;
	        HostnameVerifier oldHostnameVerifier = null;
	        boolean useHttps = URL.startsWith("https");
	        if (useHttps) {
	            conn = (HttpsURLConnection) connection;
	            oldSocketFactory = trustAllHosts(conn);
	            oldHostnameVerifier = conn.getHostnameVerifier();
	            conn.setHostnameVerifier(DO_NOT_VERIFY);
	            conn.setConnectTimeout(6*10000);
	            conn.setRequestMethod("GET");
	            conn.setUseCaches(false);
	            conn.setDoInput(true);
//	            conn.setDoOutput(true);
	            conn.setRequestProperty("Connection", "Keep-Alive");
	            conn.setRequestProperty("Charset", "UTF-8");
//	            conn.setRequestProperty("Content-Length", Integer.toString(sendText.length()));
	            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
	            
                conn.connect();
				logger.info("连接网络...");
//	            OutputStream os = conn.getOutputStream();
//	            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
//	            osw.write(sendText);
//	            osw.flush();
//	            osw.close();
//	            os.close();
	            int responseCode = conn.getResponseCode();
				if(responseCode == HttpURLConnection.HTTP_OK) {
					InputStream is = conn.getInputStream();
					byte[] buffer = new byte[521];
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					for ( int len = 0; (len = is.read(buffer)) > 0;) {
						 baos.write(buffer, 0, len);
					}
					returnValue = new String(baos.toByteArray(), "utf-8");
					baos.flush();
					baos.close();
					is.close();
				} else {
					logger.error("请求失败!responseCode: " + responseCode);
				}
	            
	        }
	        return returnValue;
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("https 请求异常!请核实请求的URL!");
			return null;
		} finally {
			if(conn != null) {
				conn.disconnect();
			}
		}
	}
	 
	/**
     * 覆盖java默认的证书验证
     */
    private static final TrustManager[] trustAllCerts = new TrustManager[]{
    	new X509TrustManager() {
        
		@Override
		public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

    }};

    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * 信任所有
     * @param connection
     * @return
     */
    private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory newFactory = sc.getSocketFactory();
            connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oldFactory;
    }
    
    public static void main(String[] args) throws Exception {
    	
    	// 请求URL
    	String url = "https://www.baidu.com";
    	new HttpsTrustCertDemo().getResponseCode(url);
    	
    	String retStr = new HttpsTrustCertDemo().testConnection(url, "hello");
    	System.out.println(retStr);
	}

}


参考文章:https://blog.csdn.net/u012527802/article/details/70172357

标签: java https X509Certificate

分享:

上一篇ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

下一篇如何实现局域网流量监控

关于我

崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。

座右铭

当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。

Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。