Android HTTPS encounters self-signed certificate/Trust certificate

Source: Internet
Author: User

For certificates issued by CA authorities okhttp default support can be accessed directly
However, for a custom certificate It is not possible (for example: https://kyfw.12306.cn/otn/), you need to join the trust
The following two parts to write, one is to trust all certificates, the second is to trust the specified certificate, access to the self-signed web site

One, trust all certificates

1. Add the Build.gradule under your module

dependencies {、、、 compile ' com.zhy:okhttputils:2.6.2 ' 、、、}

2. New MyApplication

public class MyApplication extends application {@Override public void onCreate () {super.oncreate ();        This is the trust of all certificates httpsutils.sslparams sslparams = httpsutils.getsslsocketfactory (null,null, NULL);                    Okhttpclient okhttpclient = new Okhttpclient.builder (). ConnectTimeout (10000L, Timeunit.milliseconds) . ReadTimeout (10000L, Timeunit.milliseconds). Addinterceptor (New Loggerinterceptor ("TA                        G ")). Hostnameverifier (New Hostnameverifier () {@Override                        public boolean verify (String hostname, sslsession session) {return true;                    }}). sslsocketfactory (Sslparams.sslsocketfactory, Sslparams.trustmanager)            . build ();        Okhttputils.initclient (okhttpclient);           } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }    }

3.androidmainfest.xml

Add Permissions <uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>    < Uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>    < Application        //Add the newly created MyApplication name in        android:name= ". MyApplication ".....        

4. Then where you need to request the network

public void Gethttps (view view) {        String url = "https://kyfw.12306.cn/otn/";        Okhttputils.                get ().                url (URL).                build ()                . Execute (New Stringcallback () {                    @Override                    public void OnError (call call, Exception e, int id) {                        log.e ("TAG", "OnError:" + e.tostring ());                    }                    @Override public                    void Onresponse (String response, int id) {                        log.e ("TAG", "Onresponse:" + response.tostring ()) ;                    }                });    }
Ii. Custom Certificate self-signed web site

Divided into two types: 1. Direct use of the website certificate; 2. Converting a certificate to a string

1. Direct use of website Certificate # # #

1. Export the Web site certificate
--Chrome Browser method: (Other browser please Baidu)
--Visit https://kyfw.12306.cn/otn/
Press F12
--


--More information--Copy to file--next
--Select
--Next
--Select Save location to fill in file name
 
--Next--Complete --OK
2, put the exported certificate under the Assets folder, do not create a

Used  in application httpsutils.sslparams sslparams = httpsutils.getsslsocketfactory (New Inputstream[]{getassets ( ). Open ("Srca.cer")}, NULL, NULL);

==========
You can also convert a certificate directly to a string without a certificate, using a string

2. Convert the certificate to string # # # # #

Two ways to choose a direct use certificate you don't need this step.
Code http://download.csdn.net/download/eryhytkmgfhnghnjfghn/9834086

1. Add the Build.gradule under your module

dependencies {、、、 compile ' com.zhy:okhttputils:2.6.2 ' 、、、}

2. New MyApplication

public class MyApplication extends application {///Get 12306 website Certificate, extract the contents of the certificate, write the string constant//Do not extract the content please Baidu//My in Asli is can directly see the content of Private String cer_12306 = "-----BEGIN CERTIFICATE-----\ n" + "MIICMJCCAGOGAWIBAGIIBYZR5/JKH6QWDQYJK ozihvcnaqefbqawrzelmakga1uebhmcq04xktan\n "+" Bgnvbaotifnpbm9yywlsienlcnrpzmljyxrpb24gqxv0ag9yaxr5mq0wcwydvqqde            wrtuknbmb4x\n "+" dta5mduynta2ntywmfoxdti5mduymda2ntywmfowrzelmakga1uebhmcq04xktanbgnvbaotifnp\n "+ "bm9yywlsienlcnrpzmljyxrpb24gqxv0ag9yaxr5mq0wcwydvqqdewrtuknbmigfma0gcsqgsib3\n" + "DQEBAQUAA4GNADCBiQKBgQDMpbN eb34p0gvlkz6t72/ooba4mx2k/ezrwffnuk8e5jkdh+9bgcb2\n "+" 9BSOTQPQTBXXWPXIOZ8EJYUO3BFR5PQ8OVNTOLKS2RS5BDMHOI4SUJC            ki5eliqtyww/xgy5ifqv6\n "+" d4pw9qvoucdrvsbpwo1dwmmh75it6pk/rarifhejwwidaqabo4gomiglmb8ga1udiwqymbaafhle\n "+ "tne34lkdq+3huyhmy4usaenymawga1udewqfmambaf8wlgydvr0fbccwjtajocggh4ydahr0cdov\n" + "LzE5Mi4xNjguOS4xN Dkvy3jsms5jcmwwcwydvr0pbaqdagh+mb0ga1uddgqwbbr5xrz3t+jsg0pt\n "+" x1gitgoflabdwdanbgkqhkig9w0baqufaaobgqdgram2u/of1lbong2bnnqtgcvabxivj f8lkpav\n "+" 23xq96hu8xfgszmjs6u00whai7zp0q208rsuft9wdq9ee///vohzr6tebg9qfypsohkbrhxqenvq\n "+" Og5    55s+c3ejaavenctems3n/m5hzbrjaoffn3qoydao1q8btguoi+2849a==\n "+"-----END CERTIFICATE-----";        @Override public void OnCreate () {super.oncreate (); This is the difference between trusting all certificates * * and one here *//here Import Okio.           Buffer; Httpsutils.sslparams sslparams = httpsutils.getsslsocketfactory (new inputstream[]{new Buffer (). WriteUtf8 (CER_12306)        . InputStream ()},null, NULL);                    Okhttpclient okhttpclient = new Okhttpclient.builder (). ConnectTimeout (10000L, Timeunit.milliseconds) . ReadTimeout (10000L, Timeunit.milliseconds). Addinterceptor (New Loggerinterceptor ("TA             G ")). Hostnameverifier (New Hostnameverifier () {@Override           public boolean verify (String hostname, sslsession session) {return true; }}). sslsocketfactory (Sslparams.sslsocketfactory, Sslparams.trustmana            GER). build ();        Okhttputils.initclient (okhttpclient);        } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }    }

And then the same 34

Code HTTPS://GITHUB.COM/DEADLINE837/TESTHTTPS

References Https://github.com/hongyangAndroid/okhttputils

  

Android HTTPS encounters self-signed certificate/Trust certificate

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.