Using HTTPS in Android

Source: Internet
Author: User

iOS was forced to use HTTPS last year, and both the company's iOS and Android use the same service and domain name, which requires the Android side to use HTTPS as a request.

Online find a lot of methods, here simply record:

I'm using Okhttp,google. In the latest documentation, although HTTPS is also supported, it is convenient for okhttp.

First we need to place a copy of the CA-issued certificate file locally, then in a box

1   Public Staticokhttpclient client;2    3 4     /**5 * Initialize HTTPS, add trust certificate6      * @paramContext7      */8      Public Staticokhttpclient getinstance (context context) {9Context Mcontext; Mcontext =Context.getapplicationcontext ();Ten X509trustmanager TrustManager; One sslsocketfactory sslsocketfactory; A         FinalInputStream InputStream; -         if(client==NULL) { -             Try { theInputStream = Mcontext.getassets (). Open ("Ca.crt");//the input stream that gets the certificate -                 Try { -TrustManager = Trustmanagerforcertificates (InputStream);//read the certificate in a streaming way -Sslcontext Sslcontext = sslcontext.getinstance ("TLS"); +Sslcontext.init (NULL,NewTrustmanager[]{trustmanager},NULL); -Sslsocketfactory =sslcontext.getsocketfactory (); +  A}Catch(generalsecurityexception e) { at                     Throw NewRuntimeException (e); -                 } -  -Client =NewOkhttpclient.builder () - . Sslsocketfactory (Sslsocketfactory, TrustManager) - . Build (); in  -  to}Catch(IOException e) { + e.printstacktrace (); -             } the             returnclient; *         } $         Else {Panax NotoginsengSYSTEM.OUT.PRINTLN ("Now returns an already existing instance"); -             returnclient; the         } +     } A  the      +     /** - * Add trust certificates in a streaming way $      */ $     /** - * Returns A trust manager that trusts {@codecertificates} and none other. HTTPS Services whose - * Certificates has not been signed by these certificates would fail with a {@code the * Sslhandshakeexception}. - * <p>Wuyi * <p>this can used to replace the host platform ' s built-in trusted certificates with a custom the * Set. This is useful in development where certificate authority-trusted certificates aren ' t - * available. Or in production, to avoid reliance on Third-party certificate authorities. Wu * <p> - * <p> About *  $ * <p> - * <p>relying on your own trusted certificates limits your server team ' s ability to update their - * TLS certificates. By installing a specific set of trusted certificates, you take on additional - * Operational complexity and limit your ability to migrate between certificate authorities. do A * Not use custom trusted certificates in production without the blessing of your server ' s TLS + * Administrator. the      */ -      Public StaticX509trustmanager trustmanagerforcertificates (InputStream in) $             throwsgeneralsecurityexception { theCertificatefactory certificatefactory = certificatefactory.getinstance ("the"); thecollection<?extendscertificate> certificates =certificatefactory.generatecertificates (in); the         if(Certificates.isempty ()) { the             Throw NewIllegalArgumentException ("expected Non-empty set of trusted Certificates"); -         } in  the         //Put The certificates a key store. the         Char[] Password = "password". ToCharArray ();//Any password would work . AboutKeyStore KeyStore =newemptykeystore (password); the         intindex = 0; the          for(Certificate certificate:certificates) { theString Certificatealias = integer.tostring (index++); + keystore.setcertificateentry (Certificatealias, certificate); -         } the Bayi         //Use the it to build a X509 trust manager. theKeymanagerfactory keymanagerfactory =Keymanagerfactory.getinstance ( the keymanagerfactory.getdefaultalgorithm ()); - keymanagerfactory.init (keyStore, password); -Trustmanagerfactory trustmanagerfactory =Trustmanagerfactory.getinstance ( the trustmanagerfactory.getdefaultalgorithm ()); the Trustmanagerfactory.init (keyStore); thetrustmanager[] Trustmanagers =trustmanagerfactory.gettrustmanagers (); the         if(trustmanagers.length! = 1 | |! (Trustmanagers[0]instanceofX509trustmanager)) { -             Throw NewIllegalStateException ("Unexpected default trust managers:" the+arrays.tostring (trustmanagers)); the         } the         return(X509trustmanager) Trustmanagers[0];94     } the  the  the     /**98 * Add password About      * @paramPassword -      * @return101      * @throwsgeneralsecurityexception102      */103      Public StaticKeyStore Newemptykeystore (Char[] password)throwsgeneralsecurityexception {104         Try { theKeyStore KeyStore = keystore.getinstance (Keystore.getdefaulttype ());//The custom password is added here, the default106InputStream in =NULL;//by convention, ' null ' Creates a empty key store.107 keystore.load (in, password);108             returnKeyStore;109}Catch(IOException e) { the             Throw NewAssertionerror (e);111         } the}

This is simply to encapsulate the construction HTTPS, and then in the case of a single request class

  Private MCrypt MCrypt;    public okhttpclient client;    Private Callbackfordata _backfordata;    Private String encryptstr;    Private Jsonobject jsonobj;    Public Integer userId = 0;    Private Jsonobject Jsonobjarr;        Public ExChange (Callbackfordata backfordata, Context context) {_backfordata = Backfordata;        if (httpsutils.client = = null) {httpsutils.getinstance (context);    } this.client = Httpsutils.client;        Public ExChange (Callbackfordata backfordata) {_backfordata = Backfordata;          This.client = httpsutils.client;        public void Run (String encryptstr) throws Exception {mCrypt = new mCrypt (); Request Request = new Request.builder (). URL ("https://www.xxx.com"). Post (requestbody.create (Mediatype.parse ("Application/json"), Encryptstr)).        Build (); Client.newcall (Request) Enqueue (new Callback () {@Override PUBlic void OnFailure (call call, IOException e) {System.out.println ("error" + e.getmessage ());                } @Override public void Onresponse (call call, Response Response) throws IOException {                if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response);                Headers responseheaders = Response.headers ();  for (int i = 0; i < responseheaders.size (); i++) {System.out.println (Responseheaders.name (i) + ":"                + Responseheaders.value (i));                String Data = Response.body (). String ();                COM.ANDROID.PGB.UTILS.LOG.E ("_backfordata" + thread.currentthread (). GetId ());                Jsonobject obj = null;                    try {obj = new jsonobject (Data);                    Jsonarray arr = Jsonutils.getjsonarray (obj, "data");                    String cmd = jsonutils.getstring (obj, "cmd"). toString (); int code = Jsonutils.getint (obj, "code", 0);                if (_backfordata! = null) _backfordata.onmessage (Data, cmd, code);                } catch (Jsonexception e) {e.printstacktrace ();    }            }        });    } public interface Callbackfordata {void OnMessage (string str, string cmd, int code); }}

The page numbers after that are all going to go from this class.

Above!

Using HTTPS in Android

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.