在android/app/src/main/java/com/platfrom中新增CustomOkHttpClientFactory.java
package com.platfrom; import com.facebook.react.modules.network.OkHttpClientFactory; import com.facebook.react.modules.network.ReactCookieJarContainer; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.SecureRandom; import okhttp3.OkHttpClient; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.net.ssl.KeyManager; public class CustomOkHttpClientFactory implements OkHttpClientFactory { static SSLSocketFactory sslSocketFactory; static X509TrustManager trustManager; static { trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; TrustManager[] trustAllCerts = new TrustManager[] { trustManager }; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init((KeyManager[]) null, trustAllCerts, new SecureRandom()); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } } @Override public OkHttpClient createNewNetworkModuleClient() { OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() .connectTimeout(0, TimeUnit.MILLISECONDS) .readTimeout(0, TimeUnit.MILLISECONDS) .writeTimeout(0, TimeUnit.MILLISECONDS) .cookieJar(new ReactCookieJarContainer()); clientBuilder // .sslSocketFactory(sslSocketFactory)(android10及以下) .sslSocketFactory(sslSocketFactory, trustManager) .hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { // 忽略所有的HTTPS認證,直接返回了true return true; } }); return clientBuilder.build(); } }
在MainApplication.java檔案中加入
import com.facebook.react.modules.network.OkHttpClientProvider; OkHttpClientProvider.setOkHttpClientFactory(new CustomOkHttpClientFactory());
新建一個資料夾facebook.react.modules.network,在建立一個NetworkingModuleCreateUtil.java檔案
package com.facebook.react.modules.network; import com.facebook.react.bridge.ReactApplicationContext; import okhttp3.OkHttpClient; public class NetworkingModuleCreateUtil { public static NetworkingModule create(ReactApplicationContext reactApplicationContext) { // 可以在這裡對OkHttpClient新增自己的設定,例如新增ssl的自簽名證書 OkHttpClient okHttpClient = OkHttpClientProvider.getOkHttpClient(); return new NetworkingModule(reactApplicationContext, null, okHttpClient); } }