标签:java ssl
当下的web应用好多都转到了https,有时候需要利用java发送https请求,但是呢服务器有证书,又没有好的办法得到服务器证书,一般会自定义jsse里的信任管理器,让客户端不验证服务器的证书的有效性,此方法一般就叫绕过证书之类的,下面给一个参考demo:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.NoSuchAlgorithmException; 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.TrustManager; import javax.net.ssl.X509TrustManager; /** * @Title: SSLDemo1.java * @Package * @Description: TODO(用一句话描述该文件做什么) * @author huhu * @date 2016年1月21日 上午10:08:45 * @version V1.0 */ public class SSLDemo1 { public static void main(String[] args) throws Exception { trustAllHttpsCertificates(); HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { System.out.println("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); // 在建立Https连接之前做如上处理后,后续就跟普通http处理一样 URL url = new URL("https://dynamic.12306.cn/otsweb/main.jsp"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLContext sc = SSLContext.getInstance("SSL"); conn.connect(); // BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())) ; // String input = "" ; // // while((input = br.readLine()) != null){ // System.out.println(input); // } } private static void trustAllHttpsCertificates() throws Exception{ TrustManager[] tms = new TrustManager[1]; TrustManager tm = new CustomTrustManager(); tms[0] = tm ; SSLContext context = SSLContext.getInstance("SSL"); context.init(null, tms, null); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } static class CustomTrustManager implements X509TrustManager{ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }
标签:java ssl
原文地址:http://langlichong.blog.51cto.com/8846944/1737072