HttpClient methods for ignoring user certificate validation

Source: Internet
Author: User
Tags socket static class

The program has an exception like this: Javax.net.ssl.SSLException:hostname in certificate didn ' t match. The exception occurs on this line of code: Httpclient.execute (HttpGet);
Preliminary judgment is the issue of the certificate, prepared to use the method of ignoring the certificate to solve, but in the internet for half a day did not find a reliable code to solve, and finally the solution.
To get a lesson, the Internet to find the answer is not reliable, because the specific problems need to be specific analysis, other people's methods may not be able to solve your, must think for themselves, pondering. The most important thing on the net is to find the solution to the problem, and finally to think about the specific code to solve their own problems.
Finally spit groove A sentence, the online solution is mostly nonsense a basket, half a day said not to the core solution.

Core idea: Inheriting sslsocketfactory, overriding a validation certificate always returns true for Unverifysocketfactory,
* New One such Unverifysocketfactory object is set to HttpClient. The code is as follows:


Import java.io.IOException;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import java.security.KeyManagementException;
Import Java.security.KeyStore;
Import java.security.KeyStoreException;
Import java.security.NoSuchAlgorithmException;
Import java.security.UnrecoverableKeyException;
Import java.security.cert.CertificateException;

Import Java.security.cert.X509Certificate;
Import Javax.net.ssl.SSLContext;
Import javax.net.ssl.SSLException;
Import javax.net.ssl.SSLSession;
Import Javax.net.ssl.SSLSocket;
Import Javax.net.ssl.TrustManager;

Import Javax.net.ssl.X509TrustManager;
Import org.apache.http.HttpVersion;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.conn.ClientConnectionManager;
Import Org.apache.http.conn.scheme.PlainSocketFactory;
Import Org.apache.http.conn.scheme.Scheme;
Import Org.apache.http.conn.scheme.SchemeRegistry;
Import Org.apache.http.conn.ssl.SSLSocketFactory;
Import Org.apache.http.conn.ssl.X509HostnameVerifier; Import Org.apacHe.http.impl.client.DefaultHttpClient;
Import Org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
Import Org.apache.http.params.BasicHttpParams;
Import Org.apache.http.params.HttpParams;
Import Org.apache.http.params.HttpProtocolParams;

Import Org.apache.http.protocol.HTTP;

Import Android.util.Log;
	
	/** * Tool class: Create a httpclient instance that ignores user certificate validation * @date 2015-02-13 * @author Barry */public class Certificatevalidationignored { 
	public static HttpClient getnocertificatehttpclient (String URL) {return getcertificatevalidationignoredhttpclient (); } private static HttpClient getcertificatevalidationignoredhttpclient () {try {KeyStore Trus  
            Tstore = Keystore.getinstance (KeyStore. Getdefaulttype ());  
            Truststore.load (null, NULL);
            
            The core code that creates a Unverifysocketfactory object, validates that the certificate always returns true sslsocketfactory SF = new Unverifysocketfactory (Truststore); Httpparams params = new Basichttpparams();  
            Httpprotocolparams.setversion (params, httpversion.http_1_1); Httpprotocolparams.setcontentcharset (params, HTTP.  
            UTF_8);  
            Schemeregistry Registry = new Schemeregistry ();  
            Registry.register (New Scheme ("http", Plainsocketfactory. Getsocketfactory (), 80));  
            Registry.register (New Scheme ("https", SF, 443));  
            Clientconnectionmanager ccm = new Threadsafeclientconnmanager (params, registry);  
        return new Defaulthttpclient (CCM, params);
        	} catch (Exception e) {log.d ("certificatevalidationignored", "Create a HttpClient object that ignores user certificates failed, attempt to create a normal httpclient object");
            E.printstacktrace ();  
        return new Defaulthttpclient (); }}/** * Core class * Unverifysocketfactory: A subclass of sslsocketfactory that always returns True when validating a certificate */private static X509hostname
	Verifier Ignoreverifier; private static class Unverifysocketfactory extends Sslsocketfactory{Sslcontext Sslcontext = sslcontext.getinstance ("TLS"); Public unverifysocketfactory (KeyStore truststore) throws NoSuchAlgorithmException, Keymanagementexception, KeyStor

			Eexception, unrecoverablekeyexception {super (Truststore); TrustManager TM = new X509trustmanager () {public void checkclienttrusted (x509certificate[] chain, String authty PE) throws certificateexception {} public void checkservertrusted (x509certificate[] chain, String authtype
				) throws Certificateexception {} public x509certificate[] Getacceptedissuers () {return null;

			}
			};
		Sslcontext.init (NULL, new trustmanager[] {TM}, NULL); } @Override Public Socket Createsocket (socket socket, String host, int port, Boolean autoClose) throws Ioexceptio
		N, unknownhostexception {return sslcontext.getsocketfactory (). Createsocket (socket, host, port, AutoClose); }//Core code @Override public void Sethostnameverifier (X509hostnameverifier hostNameverifier) {//TODO auto-generated method Stub ignoreverifier = new X509hostnameverifier () {@Override P ublic void Verify (String arg0, string[] arg1, string[] arg2) throws sslexception {} @Override public Vo  ID Verify (String arg0, X509Certificate arg1) throws sslexception {} @Override public void Verify (string arg0, Sslsocket arg1) throws IOException {}//most core code @Override public boolean verify (String a
				RG0, SSLsession arg1) {return true;
			}
			};
		Super.sethostnameverifier (Ignoreverifier);
		} @Override Public X509hostnameverifier gethostnameverifier () {return ignoreverifier; 
		} @Override Public Socket Createsocket () throws IOException {return sslcontext.getsocketfactory (). Createsocket (); }
	}
		
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.