简体   繁体   English

在Android中使用HTTPS与服务器连接

[英]Connect with server using HTTPS in Android

I am doing an app to connect with HTTPS Server. 我正在做一个与HTTPS服务器连接的应用程序。 I've read a lot of tutorials but i have not a ideal solution. 我读了很多教程,但是我没有理想的解决方案。

In server I've got a self-signed certificated. 在服务器中,我有一个自签名证书。 What have I to do in client part? 客户部分我要做什么? I read official tutorial: http://developer.android.com/training/articles/security-ssl.html But if I load the same certificate app crashes with this exception javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. 我阅读了官方教程: http : //developer.android.com/training/articles/security-ssl.html但是,如果我加载相同的证书,则应用程序会崩溃,但出现以下异常javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Some idea or example? 一些想法或例子?

Thanks 谢谢

You need to add it to your Request. 您需要将其添加到您的请求中。

For retrofit for example 例如改造

        OkHttpClient client = new OkHttpClient();

    try {
        KeyStore keyStore = readKeyStore(this);
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "keystore_pass".toCharArray());
        sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(), new SecureRandom());
        client.setSslSocketFactory(sslContext.getSocketFactory());

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

Then 然后

            .setClient(new OkClient(client))

To RestAdapter.Builder() 到RestAdapter.Builder()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM