赞
踩
Android 4.4 及以下,使用 OkHttp 发送 Https 请求,报以下错误:
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x6b712c90: Failure in SSL library, usually a protocol error error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x68111cd4:0x00000000) at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:448) at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302) at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270) at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162) at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257) at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135) at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114) at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x6b712c90: Failure in SSL library, usually a protocol error error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x68111cd4:0x00000000) at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method) at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405) ... 23 more
首先配制好 sslSocketFactory 和 hostnameVerifier:
import android.annotation.SuppressLint import java.net.InetAddress import java.net.Socket import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager class MySSLSocketFactory(tm: TrustManager = TrustAllTrustManager()) : SSLSocketFactory() { var internalSSLSocketFactory: SSLSocketFactory var context: SSLContext = SSLContext.getInstance("TLSv1.1") init { context.init(null, arrayOf(tm), null) internalSSLSocketFactory = context.socketFactory } override fun getDefaultCipherSuites(): Array<String> { return internalSSLSocketFactory.defaultCipherSuites } override fun createSocket(s: Socket?, host: String?, port: Int, autoClose: Boolean): Socket { val sslSocket = context.socketFactory?.createSocket(s, host, port, autoClose) as SSLSocket sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1") return sslSocket } override fun getSupportedCipherSuites(): Array<String> { return internalSSLSocketFactory.supportedCipherSuites } override fun createSocket(host: String?, port: Int): Socket { val sslSocket = context.socketFactory?.createSocket(host, port) as SSLSocket sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1") return sslSocket } override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket { val sslSocket = context.socketFactory?.createSocket(host, port, localHost, localPort) as SSLSocket sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1") return sslSocket } override fun createSocket(host: InetAddress?, port: Int): Socket { val sslSocket = context.socketFactory?.createSocket(host, port) as SSLSocket sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1") return sslSocket } override fun createSocket(address: InetAddress?, port: Int, localAddress: InetAddress?, localPort: Int): Socket { val sslSocket = context.socketFactory?.createSocket(address, port, localAddress, localPort) as SSLSocket sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1") return sslSocket } @SuppressLint("CustomX509TrustManager", "TrustAllX509TrustManager") class TrustAllTrustManager : X509TrustManager { @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { } override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } } } public class SSLSocketClient { //获取这个SSLSocketFactory public static SSLSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, getTrustManager(), new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } } //获取TrustManager private static TrustManager[] getTrustManager() { return new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}; } //获取HostnameVerifier public static HostnameVerifier getHostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; return hostnameVerifier; } }
在OkHttp中使用:
val tm = TrustAllTrustManager() val client = OkHttpClient.Builder() .sslSocketFactory( MySSLSocketFactory(tm), tm ) .hostnameVerifier(SSLSocketClient.getHostnameVerifier()) .build() val request = Request.Builder().url(url).build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.w(TAG, "onFailure: ", e) onResult(Log.getStackTraceString(e)) } override fun onResponse(call: Call, response: Response) { val result = response.body()?.string() onResult(result) } })
如果通过以上的配置,仍然报 Failure in SSL library, usually a protocol error
的错,则有以下两种解决方案:
将 OkHttp 降级到 3.9.0,即可正常请求。
在 OkHttpClient 创建的过程中,添加 ConnectionSpec 的配置,如下:
// ConnectionSpec的配置 val spec = ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ) .build() val tm = TrustAllTrustManager() val client = OkHttpClient.Builder() .connectionSpecs(Collections.singletonList(spec)) .sslSocketFactory( MySSLSocketFactory(tm), tm ) .hostnameVerifier(SSLSocketClient.getHostnameVerifier()) .build() val request = Request.Builder().url(url).build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.w(TAG, "onFailure: ", e) onResult(Log.getStackTraceString(e)) } override fun onResponse(call: Call, response: Response) { val result = response.body()?.string() onResult(result) } })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。