Android HttpClient 2 ways to handle HTTPS

Source: Internet
Author: User

The Android HTTPS or HTTP request address in the project is redirected to the address of HTTPS, believing that many people have encountered this exception (no terminal authentication):
Javax.net.ssl.SSLPeerUnverifiedException:No Peer Certificate

1. No problems encountered, search it, junior

This exception appears in log, the first time the author encounters it and does not know what it means. Look at the literal meaning that there is no terminal authentication in the SSL protocol. SSL? The author does not use the SSL protocol, just request a redirect https address via httpclient.
Well, under Google, I know a post about the situation, http://www.eoeandroid.com/thread-161747-1-1.html. NN, a good post, gives a solution. Let's try it. Add an inherited sslsocketfactory.
Custom classes. And when initializing httpclient support HTTPS, register in. Look at the following code:

public class Httpclienthelper {private static HttpClient httpclient;private Httpclienthelper () {}public static Synchronized HttpClient gethttpclient () {if (null = = HttpClient) {//Initialize work try {KeyStore Truststore = keystore.getinstance ( Keystore.getdefaulttype ()); Truststore.load (null, NULL); Sslsocketfactory SF = new Sslsocketfactoryex (truststore); Sf.sethostnameverifier (Sslsocketfactory.allow_all_  Hostname_verifier); Allow validation of all hosts httpparams params = new Basichttpparams (); Httpprotocolparams.setversion (params, httpversion.http_1_1); Httpprotocolparams.setcontentcharset (params,http. Default_content_charset); Httpprotocolparams.setuseexpectcontinue (params, true);//Set timeout for Connection Manager connmanagerparams.settimeout (params, 10000);// Set the connection timeout httpconnectionparams.setconnectiontimeout (params, 10000);//Set the socket timeout Httpconnectionparams.setsotimeout ( params, 10000);//Set HTTP HTTPS support Schemeregistry Schreg = new Schemeregistry (); Schreg.register ("http", Plainsocketfactory.getsocketfactory (), Schreg.register (nEW Scheme ("https", SF, 443)); Clientconnectionmanager Conmanager = new Threadsafeclientconnmanager (params, schreg); httpClient = new Defaulthttpclient (Conmanager, params);} catch (Exception e) {e.printstacktrace (); return new Defaulthttpclient ();}} return httpClient;}} Class Sslsocketfactoryex extends Sslsocketfactory {sslcontext sslcontext = sslcontext.getinstance ("TLS");p ublic Sslsocketfactoryex (KeyStore truststore) throws NoSuchAlgorithmException, Keymanagementexception,keystoreexception, unrecoverablekeyexception {super (Truststore); TrustManager TM = new X509trustmanager () {@Overridepublic java.security.cert.x509certificate[] getacceptedissuers () { return null;} @Overridepublic void Checkclienttrusted (java.security.cert.x509certificate[] chain, String authtype) throws java.security.cert.CertificateException {} @Overridepublic void checkservertrusted ( Java.security.cert.x509certificate[] chain, String authtype) throws java.security.cert.CertificateException {}}; Sslcontext.init (NULL, new TrustmanAger[] {TM}, null);} @Overridepublic socket Createsocket (socket socket, String host, int Port,boolean autoClose) throws IOException, Unknownho stexception {return sslcontext.getsocketfactory (). Createsocket (socket, host, port,autoclose);} @Overridepublic Socket Createsocket () throws IOException {return sslcontext.getsocketfactory (). Createsocket ();}}

Ok,run, the frantic point to the test button, a deep breath, staring at the Logat in Eclipse. Hey? The magic unexpectedly did not report before the Javax.net.ssl.SSLPeerUnverifiedException:No peer certificate abnormal. The data on the server is returned normally. , in ecstasy ...

2. Understanding and analyzing issues

In Ecstasy, you have to analyze the problem. Or the boss will ask, what's the situation? I do not know how to say (the author often this way, so learn lessons.) So understand the problems that arise, learning + reporting work).
Reasoning, the author is requesting an address that redirects https. Well, then learn to HTTPS (previously taught by the eldest, HTTP is Request/response). Keep searching, young man. The following is a summary of the HTTPS knowledge learned.

2.1 HTTPS

HTTPS: Hypertext secure transport Protocol, compared to HTTP, more than one SSL/TSL authentication process, port 443. (Despise the previous words)

The author does not use the SSL protocol, just request a redirect https address via httpclient

The 1.peer terminal sends a REQUEST,HTTPS server to return an identity information (including CA authority and encrypted public key) in the form of a certificate, such as a supported cryptographic algorithm.

2. After obtaining the certificate, verify that the certificate is legitimate.

3. Randomly generate a key and encrypt it with the public key in the certificate.

4.request HTTPS server, which transmits the key encrypted with the public key to the HTTPS service side.

5.https Server is decrypted with its own key to obtain a random value.

6. Both parties transmit the data after the communication is encrypted with this key.

Take a look at the following time series of HTTPS on the Internet:

2.2 Reasons for the problem under analysis

Well, the approximate process is known. The positioning is already very clear. You cannot verify the certificate in the 2nd step. Why can't it be verified? No trust was added. For more information, see the

Http://www.cnblogs.com/P_Chou/archive/2010/12/27/https-ssl-certification.html speaks very clearly of the HTTPS-SSL certification process, worshipping the author

In this way, the solution provided above is to add the default trust for all certificates. In order to pass the next communication.

3. Problem solving

However, this problem is solved. But it's still not safe (it's a bit risky to trust all the certificates). Continue the crackling web search. Another solution was found, and the process was roughly the same:

1. The browser accesses the HTTPS address, saves the prompt certificate to the local, and puts it into the assets directory in the Android project.

2. Import the certificate with the following code.

3. Add the certificate as trust.

String Requesthttpspage (String murl) {InputStream ins = null; String result = ""; try {ins = Context.getassets (). Open ("App_pay.cer"); The downloaded certificate is placed in the assets directory in the project certificatefactory cerfactory = Certificatefactory.getinstance ("the"); Certificate cer = cerfactory.generatecertificate (INS); KeyStore KeyStore = keystore.getinstance ("PKCS12", "BC"); Keystore.load (null, NULL); Keystore.setcertificateentry (" Trust ", CER); Sslsocketfactory socketfactory = new Sslsocketfactory (KeyStore); Scheme sch = new scheme ("https", socketfactory, 443); HttpClient mhttpclient = new Defaulthttpclient (); Mhttpclient.getconnectionmanager (). Getschemeregistry (). Register ( SCH); BufferedReader reader = null;try {log.d (TAG, "Executeget is In,murl:" + murl); HttpGet request = new HttpGet (); Request.seturi (new URI (Murl)); HttpResponse response = Mhttpclient.execute (Request), if (Response.getstatusline (). Getstatuscode ()! = 200) { Request.abort (); return result;} reader = new BufferedReader (New InputStreamReader (Response.getentity (). getcontent())); StringBuffer buffer = new StringBuffer (); String line = null;while (line = Reader.readline ())! = null) {buffer.append (line);} result = Buffer.tostring (); LOG.D (TAG, "murl=" + Murl + "\nresult =" + result);} catch (Exception e) {e.printstacktrace ();} finally {if (reader! = null) {Reader.close ();}}} catch (Exception e) {//Todo:handle Exception} finally {try {if (INS! = null) Ins.close ();} catch (IOException e) {E.print StackTrace ();}} return result;}

Next, verify the chant. Roar, the confused can again. Touched tears, found a problem: or Original Good (the author is really real to share their experience, do not know can also private messages )

Related Article

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.