OKHttp请求https证书验证

本文介绍如何在Android应用中加载自签名证书srca.cer,并将其用于创建SSL连接,实现对特定HTTPS服务的安全访问。通过使用OkHttp库定制SSL套接字工厂,应用程序可以信任预置的自签名证书,确保与指定服务器之间的通信安全。

拿到srca.cer证书放入assets文件中

private static SSLSocketFactory sslSocketFactory = null;
public static void getSocketFactory() {
    try {
        InputStream certificate = MyApplication.mContext.getAssets().open("srca.cer");
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

        try {
            if (certificate != null)
                certificate.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

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

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

        sslSocketFactory = sslContext.getSocketFactory();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * get请求
 **/
public void sendGetRepuest(String url, final CallBacks callbacks) {
    final Request request = new Request.Builder().url(url).build();
    client.newBuilder().connectTimeout(timeOut, TimeUnit.SECONDS)
            .readTimeout(timeOut, TimeUnit.SECONDS)
            .writeTimeout(timeOut, TimeUnit.SECONDS)
            .sslSocketFactory(sslSocketFactory)//设置sslSocketFactory
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            callbacks.onError(e.toString());
        }

        //解析成功
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response != null && response.isSuccessful()) {
                callbacks.onSuccess(response.body().string());
            } else {
                callbacks.onError(response.toString());
            }
        }
    });
}

public class MyApplication extends Application {

    public static Context mContext = null;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        OkHttpUtils.getSocketFactory();
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值