在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); } }
标签:请求,javax,React,ssl,Https,new,import,net,public From: https://www.cnblogs.com/Lemon111/p/18597466