转发到webhook时忽略ssl证书校验(提高自建服务端兼容性)

This commit is contained in:
pppscn 2021-04-21 11:23:37 +08:00
parent 9a0f26a7a3
commit a28fd0d4d8
2 changed files with 76 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import com.idormy.sms.forwarder.utils.CertUtils;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
@ -70,7 +71,11 @@ public class SenderWebNotifyMsg {
request = new Request.Builder().url(webServer).method("POST", body).build();
}
OkHttpClient client = new OkHttpClient().newBuilder().build();
OkHttpClient client = new OkHttpClient().newBuilder()
//忽略https证书
.sslSocketFactory(CertUtils.getSSLSocketFactory(), CertUtils.getX509TrustManager())
.hostnameVerifier(CertUtils.getHostnameVerifier())
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override

View File

@ -0,0 +1,70 @@
package com.idormy.sms.forwarder.utils;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class CertUtils {
//获取这个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[]{};
}
}
};
}
//获取HostnameVerifier
public static HostnameVerifier getHostnameVerifier() {
return (s, sslSession) -> true;
}
public static X509TrustManager getX509TrustManager() {
X509TrustManager trustManager = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
trustManager = (X509TrustManager) trustManagers[0];
} catch (Exception e) {
e.printStackTrace();
}
return trustManager;
}
}