无法通过Volley发出HTTPS请求

时间:2018-11-06 09:51:57

标签: java android ssl https

我正在尝试将一些数据从我的android应用程序发布到实时服务器,而我正在使用凌空来实现这一点。当我发布到HTTP时,它工作正常,但是当我尝试使用HTTPS时,向我显示此错误:

  

com.android.volley.NoConnectionError:javax.net.ssl.SSLHandshakeException:javax.net.ssl.SSLProtocolException:SSL握手中止:

我有SSL证书和来自服务器的密钥(my_cert.crt和my_key.key)。

我使用的方法如下:

private SSLSocketFactory getSocketFactory() {

CertificateFactory cf = null;
try {

    cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = getResources().openRawResource(R.raw.my_cert);
    Certificate ca;
    try {

        ca = cf.generateCertificate(caInput);
        Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }


    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);


    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);


    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {

            Log.e("CipherUsed", session.getCipherSuite());
            return hostname.compareTo("example.domain.com")==0; 

        }
    };


    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    SSLContext context = null;
    context = SSLContext.getInstance("TLS");

    context.init(null, tmf.getTrustManagers(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

    SSLSocketFactory sf = context.getSocketFactory();


    return sf;

} catch (CertificateException e) {
    e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
} catch (KeyStoreException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (KeyManagementException e) {
    e.printStackTrace();
}

return  null;
}

我用以下几行代码来称呼它:

RequestQueue requestQueue = Volley.newRequestQueue(this, new HurlStack(null, getSocketFactory()));
requestQueue.add(stringRequest);

我还添加了res / xml / network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.domain.com</domain>
        <trust-anchors>
            <certificates src="@raw/my_cert"/>
        </trust-anchors>
    </domain-config>
</network-security-config>

我做错什么了吗?为什么我不能发出HTTPS请求并发布数据?

0 个答案:

没有答案