我试图连接到一个运行godaddy 256bit SSL证书的IIS6盒子,我得到了错误:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

我一直在想是什么原因导致的,但目前还没有头绪。

以下是我的联系方式:

HttpsURLConnection conn;              
conn = (HttpsURLConnection) (new URL(mURL)).openConnection();
conn.setConnectTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
String tempString = toString(conn.getInputStream());

@Chrispix的解决方案是危险的!相信所有的证书允许任何人做一个人在中间攻击!只要向客户端发送任何证书,它就会接受它!

将您的证书添加到自定义信任管理器,如本文所述:通过HTTPS使用HttpClient信任所有证书

虽然使用自定义证书建立安全连接有点复杂,但它将为您带来所需的ssl加密安全,而没有中间人攻击的危险!


与公认的答案相反,您不需要自定义信任管理器,您需要修复您的服务器配置!

我在连接Apache服务器时遇到了同样的问题,该服务器错误地安装了dynadot/alphassl证书。我正在使用HttpsUrlConnection (Java/Android)连接,这是抛出-

javax.net.ssl.SSLHandshakeException: 
  java.security.cert.CertPathValidatorException: 
    Trust anchor for certification path not found.

实际的问题是服务器配置错误——用http://www.digicert.com/help/或类似工具测试,它甚至会告诉你解决方案:

证书不是由受信任的权威机构签署的(根据Mozilla的根存储进行检查)。如果您从受信任的权威机构购买了证书,则可能只需要安装一个或多个中间证书。请与您的证书提供商联系,以便在您的服务器平台上执行此操作。”

您也可以在openssl中查看证书:

Openssl s_client -debug -connect www.thedomaintocheck.com:443

你可能会看到:

验证返回码:21(无法验证第一个证书)

在前面的输出中:

depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=27:certificate not trusted
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=21:unable to verify the first certificate`

证书链将只包含1个元素(您的证书):

Certificate chain
 0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
  i:/O=AlphaSSL/CN=AlphaSSL CA - G2

... 但是应该引用链中的签名授权,回到Android信任的授权(Verisign, GlobalSign等):

Certificate chain
 0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
   i:/O=AlphaSSL/CN=AlphaSSL CA - G2
 1 s:/O=AlphaSSL/CN=AlphaSSL CA - G2
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
 2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA

配置服务器的说明(和中间证书)通常由颁发证书的机构提供,例如:http://www.alphassl.com/support/install-root-certificate.html

在安装了我的证书颁发者提供的中间证书之后,我现在在使用HttpsUrlConnection连接时没有错误。


我得到的错误消息与此类似,但原因是自签名证书已经过期。 当尝试openssl客户端时,它给了我一个原因,当我在firefox中检查证书对话框时忽略了这个原因。

因此,通常情况下,如果证书在密钥存储库中并且它是“VALID”,则此错误将消失。


在姜饼手机,我总是得到这个错误:信任锚没有找到Android SSL连接,即使我设置依赖于我的证书。

下面是我使用的代码(在Scala语言中):

object Security {
    private def createCtxSsl(ctx: Context) = {
        val cer = {
            val is = ctx.getAssets.open("mycertificate.crt")
            try
                CertificateFactory.getInstance("X.509").generateCertificate(is)
            finally
                is.close()
        }
        val key = KeyStore.getInstance(KeyStore.getDefaultType)
        key.load(null, null)
        key.setCertificateEntry("ca", cer)

        val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    tmf.init(key)

        val c = SSLContext.getInstance("TLS")
        c.init(null, tmf.getTrustManagers, null)
        c
    }

    def prepare(url: HttpURLConnection)(implicit ctx: Context) {
        url match {
            case https: HttpsURLConnection ⇒
                val cSsl = ctxSsl match {
                    case None ⇒
                        val res = createCtxSsl(ctx)
                        ctxSsl = Some(res)
                        res
                    case Some(c) ⇒ c
                }
                https.setSSLSocketFactory(cSsl.getSocketFactory)
            case _ ⇒
        }
    }

    def noSecurity(url: HttpURLConnection) {
        url match {
            case https: HttpsURLConnection ⇒
                https.setHostnameVerifier(new HostnameVerifier {
                    override def verify(hostname: String, session: SSLSession) = true
                })
            case _ ⇒
        }
    }
}

下面是连接代码:

def connect(securize: HttpURLConnection ⇒ Unit) {
    val conn = url.openConnection().asInstanceOf[HttpURLConnection]
    securize(conn)
    conn.connect();
    ....
}

try {
    connect(Security.prepare)
} catch {
    case ex: SSLHandshakeException /*if ex.getMessage != null && ex.getMessage.contains("Trust anchor for certification path not found")*/ ⇒
        connect(Security.noSecurity)
}

基本上,我在自定义证书上设置了信任。如果失败,我就禁用安全机制。这不是最好的选择,但这是我所知道的对于老旧和有问题的手机的唯一选择。

这个示例代码,可以很容易地翻译成Java。


我有同样的问题,我发现我提供的证书.crt文件缺少一个中间证书。所以我从我的服务器管理员那里询问了所有的.crt文件,然后按相反的顺序将它们连接起来。

前女友。 1. crt 2. Inter.crt 3.myCrt.crt

在Windows中执行 复制国际米兰。crt + Root。crt newCertificate.crt

(这里我忽略了myCrt.crt)

然后我提供了newCertificate。CRT文件通过输入流转换成代码。 工作。


**Set proper alias name**
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
            String alias = cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);

您可以在运行时信任特定的证书。 只需从服务器下载,放入资产,然后使用ssl-utils-android像这样加载:

OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());

在上面的例子中,我使用了OkHttpClient,但是SSLContext可以用于Java中的任何客户端。

如果你有任何问题,请提出来。我是这个小图书馆的作者。


根据最新的Android文档(2017年3月)更新:

当你得到这种类型的错误:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
        at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
        at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
        at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
        at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
        at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
        at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)

问题可能是以下情况之一:

颁发服务器证书的CA未知 服务器证书不是由CA签署的,而是自签署的 服务器配置缺少一个中间CA

解决方案是教会HttpsURLConnection信任一组特定的ca。怎么做?请查看https://developer.android.com/training/articles/security-ssl.html#CommonProblems

其他使用com.loopj的AsyncHTTPClient的人。android:android-async-http库,请检查设置AsyncHttpClient使用HTTPS。


我在从Android客户端连接到Kurento服务器时遇到了同样的问题。 Kurento服务器使用jks证书,所以我必须将pem转换为它。 作为转换的输入,我使用cert.pem文件,它会导致这样的错误。 但如果使用全链。pem,而不是cert.pem - all是OK的。


回复一个很旧的帖子。但也许它会帮助一些新手,如果以上都行不通的话。

解释:我知道没人想听废话解释;而是解决方案。但是在一行代码中,您试图从本地计算机访问服务到不信任您的计算机的远程计算机。您的请求需要获得远程服务器的信任。

解决方案:下面的解决方案假设您满足以下条件

试图从本地机器访问远程api。 你正在为Android应用开发 您的远程服务器在代理过滤下(您在浏览器设置中使用代理来访问远程api服务,通常是登台或开发服务器) 你是在真实的设备上测试

步骤:

你需要一个.keystore扩展文件来注册你的应用。如果你不知道如何创建.keystore文件;然后按照以下小节创建.keystore文件,否则跳转到下一小节签署Apk文件

创建.keystore文件

打开Android Studio。单击顶部菜单Build > Generate Signed APK。在下一个窗口中单击Create new…按钮。在新窗口中,请在所有字段中输入数据。记住我建议的两个密码字段应该有相同的密码;不要使用不同的密码;并且记住最上面字段的保存路径键存储路径:。输入所有字段后单击OK按钮。

签署Apk文件

现在需要使用刚才创建的.keystore文件构建一个签名应用程序。遵循以下步骤

Build > Clean Project, wait till it finish cleaning Build > Generate Signed APK Click Choose existing... button Select the .keystore file we just created in the Create .keystore file section Enter the same password you created while creating in Create .keystore file section. Use same password for Key store password and Key password fields. Also enter the alias Click Next button In the next screen; which might be different based on your settings in build.gradle files, you need to select Build Types and Flavors. For the Build Types choose release from the dropdown For Flavors however it will depends on your settings in build.gradle file. Choose staging from this field. I used the following settings in the build.gradle, you can use the same as mine, but make sure you change the applicationId to your package name productFlavors { staging { applicationId "com.yourapplication.package" manifestPlaceholders = [icon: "@drawable/ic_launcher"] buildConfigField "boolean", "CATALYST_DEBUG", "true" buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "true" } production { buildConfigField "boolean", "CATALYST_DEBUG", "false" buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "false" } } Click the bottom two Signature Versions checkboxes and click Finish button.

几乎有:

所有艰苦的工作都完成了,现在是真理的运动。为了访问通过代理备份的登台服务器,您需要在您的实际测试Android设备中进行一些设置。

Android设备的代理设置:

点击Android手机内的设置,然后点击wi-fi 长按已连接的wifi,选择“修改网络” 如果看不到代理主机名字段,则单击高级选项 在代理主机名中输入要连接的主机IP或名称。典型的登台服务器将命名为stg.api.mygoodcompany.com 端口输入四位数端口号,例如9502 点击保存按钮

最后一站:

记住,我们在签名apk文件部分生成了签名apk文件。现在是时候安装APK文件了。

打开终端,更改为已签名的apk文件夹 将你的Android设备连接到你的机器 从Android设备中删除之前安装的apk文件 执行adb安装apk文件的名称 如果由于某种原因,上述命令返回adb命令没有找到。填写完整路径为:C:\Users\shah\AppData\Local\Android\sdk\platform-tools\adb.exe安装apk文件的名称

我希望问题能得到解决。如果没有,请给我留言。

萨拉姆!


在我的例子中,这发生在更新到Android 8.0之后。Android设置为信任的自签名证书使用的是签名算法SHA1withRSA。切换到新的证书,使用签名算法sha256withthrsa解决了这个问题。


产生信任锚错误的原因有很多。对我来说,我只是想访问https://example.com/而不是https://www.example.com/。

因此,在开始构建自己的信任管理器(就像我做的那样)之前,您可能需要仔细检查您的url。


我知道你不需要信任所有的证书,但在我的案例中,我在一些调试环境中遇到了问题,我们有自签名证书,我需要一个脏的解决方案。

我所要做的就是改变sslContext的初始化

mySSLContext.init(null, trustAllCerts, null); 

其中trustAllCerts是这样创建的:

private final TrustManager[] trustAllCerts= new TrustManager[] { new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[]{};
    }

    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }
} };

希望这能派上用场。


如果你使用了改装,你需要定制你的OkHttpClient。

retrofit =新的retrofit . builder () .baseUrl (ApplicationData.FINAL_URL) .build .client (getUnsafeOkHttpClient () ()) .addConverterFactory (GsonConverterFactory.create ()) .build ();

完整代码如下。

public class RestAdapter {

    private static Retrofit retrofit = null;
    private static ApiInterface apiInterface;

    public static OkHttpClient.Builder getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
            };
    
                // Install the all-trusting trust manager
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    
                // Create an ssl socket factory with our all-trusting manager
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                builder.hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                return builder;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        
        public static ApiInterface getApiClient() {
            if (apiInterface == null) {
    
                try {
                    retrofit = new Retrofit.Builder()
                            .baseUrl(ApplicationData.FINAL_URL)
                            .client(getUnsafeOkHttpClient().build())
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
    
                } catch (Exception e) {
    
                    e.printStackTrace();
                }
    
    
                apiInterface = retrofit.create(ApiInterface.class);
            }
            return apiInterface;
        }
        
    }

我也遇到过类似的问题,我已经完全排除了相信所有消息来源的策略。

我在这里分享我在Kotlin中实现的应用程序中的解决方案

我首先建议使用以下网站获取有关证书及其有效性的信息

如果它不在Android默认信任存储中显示为“已接受的发行者”,我们必须获得该证书并将其合并到应用程序中以创建自定义信任存储

在我的案例中,理想的解决方案是创建一个高级信任管理器,它结合了自定义和Android默认信任存储

在这里,他公开了用于配置他与Retrofit一起使用的OkHttpClient的高级代码。

override fun onBuildHttpClient(httpClientBuild: OkHttpClient.Builder) {

        val trustManagerWrapper = createX509TrustManagerWrapper(
            arrayOf(
                getCustomX509TrustManager(),
                getDefaultX509TrustManager()
            )
        )

        printX509TrustManagerAcceptedIssuers(trustManagerWrapper)

        val sslSocketFactory = createSocketFactory(trustManagerWrapper)
        httpClientBuild.sslSocketFactory(sslSocketFactory, trustManagerWrapper)

    }

通过这种方式,我可以使用自签名证书与服务器通信,也可以使用受信任的证书实体颁发的证书与其他服务器通信

就是这个,我希望它能帮助到一些人。


我知道这是一篇非常古老的文章,但我在尝试解决信任锚问题时遇到了这篇文章。我已经发布了我是如何修复它的。如果您已经预安装了根CA,则需要向清单中添加配置。

https://stackoverflow.com/a/60102517/114265


使用https://www.ssllabs.com/ssltest/测试域。

Shihab Uddin在Kotlin的解决方案。

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*
import javax.security.cert.CertificateException

object {

    val okHttpClient: OkHttpClient
    val gson: Gson
    val retrofit: Retrofit

    init {

        okHttpClient = getOkHttpBuilder()
            // Other parameters like connectTimeout(15, TimeUnit.SECONDS)
            .build()

        gson = GsonBuilder().setLenient().create()

        retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    fun getOkHttpBuilder(): OkHttpClient.Builder =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            OkHttpClient().newBuilder()
        } else {
            // Workaround for the error "Caused by: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at".
            getUnsafeOkHttpClient()
        }

    private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
        try {
            // Create a trust manager that does not validate certificate chains
            val trustAllCerts: Array<TrustManager> = arrayOf(
                object : X509TrustManager {
                    @Throws(CertificateException::class)
                    override fun checkClientTrusted(chain: Array<X509Certificate?>?,
                                                    authType: String?) = Unit

                    @Throws(CertificateException::class)
                    override fun checkServerTrusted(chain: Array<X509Certificate?>?,
                                                    authType: String?) = Unit

                    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                }
            )
            // Install the all-trusting trust manager
            val sslContext: SSLContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            // Create an ssl socket factory with our all-trusting manager
            val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
            val builder = OkHttpClient.Builder()
            builder.sslSocketFactory(sslSocketFactory,
                trustAllCerts[0] as X509TrustManager)
            builder.hostnameVerifier { _, _ -> true }
            builder
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
}

如果你使用Glide,同样的错误也会出现,图像不会显示。要克服它,请参阅Glide - javax.net.ssl.SSLHandshakeException: java.security. cert.certpathvalidatorexcexception:未找到认证路径的信任锚以及如何为Glide设置OkHttpClient。

@GlideModule
class MyAppGlideModule : AppGlideModule() {

    val okHttpClient = Api.getOkHttpBuilder().build() // Api is the class written above.
    // It is better to create okHttpClient here and not use Api.okHttpClient,
    // because their settings may differ. For instance, it can use its own
    // `addInterceptor` and `addNetworkInterceptor` that can affect on a read JSON.


    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        registry.replace(GlideUrl::class.java, InputStream::class.java,
            OkHttpUrlLoader.Factory(okHttpClient))
    }
}

build.gradle:

// Glide.
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.11.0'

更新

我还在API 16模拟器上得到了另一个错误:

SSL23_GET_SERVER_HELLO:tlsv1警报协议版本 (外部/ openssl / ssl / s23_clnt.c: 741”。

阅读1和2,我修改代码如下:

okHttpClient = getOkHttpBuilder().build()

private fun getOkHttpBuilder(): OkHttpClient.Builder {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        Security.insertProviderAt(Conscrypt.newProvider(), 1)
    }
    return OkHttpClient().newBuilder()
}

// build.gradle:
implementation 'org.conscrypt:conscrypt-android:2.5.1'

我还从MyApplication中删除了这些行:

try {
    ProviderInstaller.installIfNeeded(applicationContext)
    val sslContext = SSLContext.getInstance("TLSv1.2")
    sslContext.init(null, null, null)
    sslContext.createSSLEngine()
} catch (e: GooglePlayServicesRepairableException) {
    Timber.e(e.stackTraceToString())
    // Prompt the user to install/update/enable Google Play services.
    GoogleApiAvailability.getInstance().showErrorNotification(this, e.connectionStatusCode)
} catch (e: GooglePlayServicesNotAvailableException) {
    Timber.e(e.stackTraceToString())
    // Prompt the user to install/update/enable Google Play services.
    // GoogleApiAvailability.getInstance().showErrorNotification(this, e.errorCode)
} catch (e: NoSuchAlgorithmException) {
    Timber.e(e.stackTraceToString())
} catch (e: KeyManagementException) {
    Timber.e(e.stackTraceToString())
}

但是这个库给apk增加了3.4 Mb。


有时,当管理员错误地设置证书时,会发生这种情况 点击此处查看URL https://www.sslshopper.com/ssl-checker.html

在我的例子中,出现了一个错误

证书在所有浏览器中都不受信任。您可能需要安装中间证书/链证书以将其链接到受信任的根证书。了解关于此错误的更多信息。您可以按照GlobalSign针对您的服务器平台的证书安装说明来解决这个问题。注意中级证书部分。


In my case, the root & intermediate certificates was successfully installed but I still got "Trust anchor for certification path not found." exception!. After digging the android document, found out that by default, secure connections (using protocols like TLS and HTTPS) from all apps trust the pre-installed system CAs, and apps targeting Android 6.0 (API level 23) and lower also trust the user-added CA store by default. If your app running on a OS with api level higher than 23 you should explicitly allow the app to trust user-added CA by adding its address to network_security_config like bellow:

<domain-config>
        <domain includeSubdomains="true">PUT_YOUR_SERVER_ADDERESS</domain>
        <trust-anchors>
            <certificates src="user" />
        </trust-anchors>
</domain-config>

我使用这些方法,其中一个是上述解决方案对我有效: 第一:

   public  okhttp3.OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate 
   certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void 
   checkClientTrusted(java.security.cert.X509Certificate[] chain, 
   String authType) throws CertificateException {
                    }

                    @Override
                    public void 
  checkServerTrusted(java.security.cert.X509Certificate[] chain, 
  String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] 
   getAcceptedIssuers() {
                        return new 
  java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = 
  SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new 
  java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting 
       manager
        final SSLSocketFactory sslSocketFactory = 
       sslContext.getSocketFactory();

        okhttp3.OkHttpClient.Builder builder = new 
      okhttp3.OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, 
      (X509TrustManager)trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession 
       session) {
                return true;
            }
        });

        okhttp3.OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

第二:

    @SuppressLint("TrulyRandom")
    public static void handleSSLHandshake() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[]{new 
       X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] 
        certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] 
       certs, String authType) {
            }
        }};

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        



  HttpsURLConnection
 .setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new 
    HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception ignored) {
    }
}

和: 把这些库放到你的类路径中:

 implementation 'com.squareup.okhttp:okhttp:2.3.0'
implementation 'com.squareup.okhttp:okhttp-urlconnection:2.3.0'
    androidTestImplementation 'androidx.test.espresso:espresso- 
    core:3.3.0'

一定要在课堂上给他们打电话


复述你的陈词滥调 var httpClient = new httpClient (new System.Net.Http.HttpClientHandler());

将https更改为http


在我的情况下,网站中的证书是正确的(发行人= GlobalSign RSA OV SSL CA 2018),但我下载的证书文件是错误的,因为防病毒正在“拦截”证书,并提供一个新的不同的证书从浏览器下载(发行人= ESET SSL过滤器CA) !!

检查证书文件的颁发者是否正确。