Android development can connect HTTPS addresses with key, but when there is no key, you can trust any host to connect to HTTPS addresses with the following methods:
a httpsurlconnection:
Import Java.security.SecureRandom;
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.X509TrustManager; private void Trusteveryone () {try {httpsurlconnection.setdefaulthostnameverifier) (new Hostnamev
Erifier () {public boolean verify (String hostname, sslsession session) {
return true;
}});
Sslcontext context = sslcontext.getinstance ("TLS"); Context.init (NULL, New X509trustmanager[]{new X509trustmanager () {public void checkclienttrusted (
X509certificate[] chain, String authtype) throws Certificateexception {} public void checkservertrusted (X509Certificate[] chain, String authtype) throws Certificateexception {} Public x509certificate[] Getacceptedissuers () {return new x509certificate[0
];
}}, New SecureRandom ());
Httpsurlconnection.setdefaultsslsocketfactory (Context.getsocketfactory ());
catch (Exception e) {//should never happen e.printstacktrace ();
}
}
two defaulthttpclient
There is a constructor in the Sslsocketfactory in Android:
/**
* Constructs an httpclient sslsocketfactory backed by the given JSSE
* Sslsocketfactory.
*
* @hide
*/
Public sslsocketfactory (Javax.net.ssl.SSLSocketFactory socketfactory) {
Super ();
This.sslcontext = null;
This.socketfactory = socketfactory;
This.nameresolver = null;
}
But it's hide. So the Sslsocketfactory source code is copied out and let go of this function. Named Mysslsocketfactory. A mysslsocketfactory can be constructed as follows:
Private Mysslsocketfactory Newsslsocketfactory () {try {sslcontext context = sslcontext.getinstance ("TLS"); Context.init (NULL, new x509trustmanager[] {new X509trustmanager () {public void checkclienttrusted (x509certificate[) Chain, String authtype) throws certificateexception {} public void checkservertrusted (x509certificate[] Ch
Ain, String authtype) throws certificateexception {} public x509certificate[] Getacceptedissuers () {
return new x509certificate[0];
}}, New SecureRandom ()); Pass the KeyStore to the sslsocketfactory.
The factory is//responsible//For the verification of the server certificate.
Mysslsocketfactory SF = new Mysslsocketfactory (Context.getsocketfactory ()); Hostname verification from certificate//http://hc.apache.org/httpcomponents-client-ga/tutorial/html/
connmgmt.html#d4e506 Sf.sethostnameverifier (Sslsocketfactory.strict_hostname_verifier);
return SF; catch (EXception e) {throw new Assertionerror (e); }
}
This also solves the problem of connecting HTTPS with Defaulthttpclient in Android.