android通过okhttp访问自签名https网站(单向)

参考:http://blog.csdn.net/lmj623565791/article/details/48129405

一、概述

okhttp可以直接访问https://www.baidu.com等通过CA认证的网站。
自签名网站:通过keytool生成证书,但是还没通过CA认证。

二、实现步骤

1、生成服务器私钥证书server.jks

> keytool -genkey -keyalg RSA  -alias server -keystore server.jks -validity 3650  

注意:姓名和性别位置要写服务器的ip或者域名,否则okhttp会报异常

2、生成服务器公钥证书server.cer

> keytool -export -alias server -file server.cer -keystore server.jks

3、将server.cer放在android项目的assets

4、设置okHttpClient

    private static void setCertificates(InputStream is) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            keyStore.setCertificateEntry("0", certificateFactory.generateCertificate(is);

            SSLContext sslContext = SSLContext.getInstance("TLS");

            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());


            okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

其中,inputstream可以由context.getAssets().open("server.cer")获得,也可以将server.cer转化为字符串,再转为inputstream

> keytool -printcert -rfc -file server.cer

-----BEGIN CERTIFICATE-----
MIICmjCCAgOgAwIBAgIIbyZr5/jKH6QwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ04xKTAn
BgNVBAoTIFNpbm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMB4X
DTA5MDUyNTA2NTYwMFoXDTI5MDUyMDA2NTYwMFowRzELMAkGA1UEBhMCQ04xKTAnBgNVBAoTIFNp
bm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMIGfMA0GCSqGSIb3
DQEBAQUAA4GNADCBiQKBgQDMpbNeb34p0GvLkZ6t72/OOba4mX2K/eZRWFfnuk8e5jKDH+9BgCb2
9bSotqPqTbxXWPxIOz8EjyUO3bfR5pQ8ovNTOlks2rS5BdMhoi4sUjCKi5ELiqtyww/XgY5iFqv6
23XQ96HU8xfgSZMJS6U00WHAI7zp0q208RSUft9wDq9ee///VOhzR6Tebg9QfyPSohkBrhXQenvQ
og555S+C3eJAAVeNCTeMS3N/M5hzBRJAoffn3qoYdAO1Q8bTguOi+2849A==
-----END CERTIFICATE-----

string转inputstream

new Buffer().writeUtf8(str).inputStream()

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(android,https,okhttp)