HTTPS support for Volley Android networking library

后端 未结 1 1434
孤街浪徒
孤街浪徒 2020-12-17 07:20

I have a project making REST calls to an HTTPS backend It which works fine on some devices, and breaks on others.

This is the error I get:

co

相关标签:
1条回答
  • 2020-12-17 07:40

    Here's my solution:

    In class Volley in method

    public static RequestQueue newRequestQueue(Context context, HttpStack stack)
    

    locate the following text:

    stack = new HurlStack();
    

    Then change this line to:

    stack = new HurlStack(null, createSslSocketFactory());
    

    where method createSslSocketFactory() is defined as following:

    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
    
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
    
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
    
        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
    
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            Log.e(TAG, StringUtils.EMPTY, e);
        } catch (KeyManagementException e) {
            Log.e(TAG, StringUtils.EMPTY, e);
        }
    
        return sslSocketFactory;
    }
    

    I know that this is not secure, but I use it for testing purposes only. You can improve the security by accepting only certificates from your servers.

    0 讨论(0)
提交回复
热议问题