低于Api级别23的SSL问题

时间:2018-09-15 11:52:33

标签: android ssl https android-volley tls1.2

我正在使用Volley库,在Api 23级以上可以正常工作。在Api 23级以下,有时响应成功有时是错误。

错误:com.android.volley.NoConnectionError:java.net.UnknownHostException

这是我实现了凌空库的代码。

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            HurlStack stack = null;
            try {
               stack = new HurlStack(null, new TLSSocketFactory());
        } catch (KeyManagementException e) {
            e.printStackTrace();
            Log.d("Your Wrapper Class", "Could not create new stack for TLS v1.2");
            stack = new HurlStack();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            Log.d("Your Wrapper Class", "Could not create new stack for TLS v1.2");
            stack = new HurlStack();
        }
        queue = Volley.newRequestQueue(mActivity, stack);
    } else {
        queue = Volley.newRequestQueue(mActivity);
    }

TLSSocketFactory.class-我用于ssl的此类。

 private SSLSocketFactory internalSSLSocketFactory;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    internalSSLSocketFactory = context.getSocketFactory();
}

@Override
public String[] getDefaultCipherSuites() {
    return internalSSLSocketFactory.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return internalSSLSocketFactory.getSupportedCipherSuites();
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    }
    return socket;
}

}

0 个答案:

没有答案