解决javax.net.ssl.SSLProtocolExcep
在使用android4.4的手机时,请求https接口发现抛出了此异常,因为在android4.4及以下的手机默认会关闭tls1.1或者tls1.2的支持,所以我们需要手动去开启对tls1.1和tls1.2的支持。
解决办法如下(部分代码):
```
```mBuilder =new OkHttpClient.Builder();
// OkHttpClient.Builder的配置代码省略
//android4.4及以下的手机默认不支持tls1.1或者tls1.2,需要手动开启
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
SSLContext sslContext =null;
try {
sslContext = SSLContext.getInstance("TLS");
try {
sslContext.init(null, null, null);
}catch (KeyManagementException e) {
e.printStackTrace();
}
}catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
SSLSocketFactory socketFactory =new Tls12SocketFactory(sslContext.getSocketFactory());
mBuilder.sslSocketFactory(socketFactory, new UnSafeTrustManager());
}
public class Tls12SocketFactoryextends SSLSocketFactory {
private static final String[]TLS_SUPPORT_VERSION = {"TLSv1.1", "TLSv1.2"};
final SSLSocketFactorydelegate;
public Tls12SocketFactory(SSLSocketFactory base) {
this.delegate = base;
}
@Override
public String[]getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[]getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public SocketcreateSocket(Socket s, String host, int port, boolean autoClose)throws IOException {
return patch(delegate.createSocket(s, host, port, autoClose));
}
@Override
public SocketcreateSocket(String host, int port)throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port));
}
@Override
public SocketcreateSocket(String host, int port, InetAddress localHost, int localPort)throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public SocketcreateSocket(InetAddress host, int port)throws IOException {
return patch(delegate.createSocket(host, port));
}
@Override
public SocketcreateSocket(InetAddress address, int port, InetAddress localAddress, int localPort)throws IOException {
return patch(delegate.createSocket(address, port, localAddress, localPort));
}
private Socketpatch(Socket s) {
if (sinstanceof SSLSocket) {
((SSLSocket) s).setEnabledProtocols(TLS_SUPPORT_VERSION);
}
return s;
}
}
public class UnSafeTrustManagerimplements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public X509Certificate[]getAcceptedIssuers()
{
return new X509Certificate[]{};
}
}```
```