The current Web application a lot of the switch to HTTPS, sometimes need to use Java to send HTTPS requests, but the server has a certificate, and there is no good way to get the server certificate, the general will customize the trust manager in the Jsse, so that the client does not verify the validity of the server's certificate, This method is generally called bypassing the certificate and the like, here is a reference to the 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 (describe the file in a word) * @author huhu * @date 2016 January 21 Morning 10:08:45 * @version v1.0 */public class ssldemo1 {public static void main ( String[] args) throws exception {trustallhttpscertificates (); Hostnameverifier hv = new hostnameverifier () {@OverRidepublic boolean verify (string hostname, sslsession session) { System.out.println ("warning: url host: " + hostname + " vs. " + session.getpeerhost ()); return true; }}; Httpsurlconnection.setdefaulthostnameverifier (HV);// After the HTTPS connection is established, the follow-up is the same as normal HTTP processing 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{@Overridepublic void checkclienttrusted (X509certificate[] chain, string authtype) throws certificateexception {} @Overridepublic void checkservertrusted (X509certificate[] chain, string authtype) throws certificateexception {} @Overridepublic x509certificate[] getacceptedissuers () {return null;}}
Java SSL Simple Operation demo