HTTPS support for Volley Android networking librar

2019-01-24 22:57发布

问题:

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:

com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x78004ee8: Failure in SSL library, usually a protocol error error:140770FCSL routinesSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:766 0x731f5d5c:0x00000000)

Looking at the Volley documentation, they mention

"You can include your own HTTPStack ( to handle SSL connections [...])"

Has someone done this for volley ? If so can you please share your changes ?

Notes: The Certificate is signed by a valid entity which was already in the trusted certificates of the devices.

回答1:

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.