Android Studio - 服务器证书过期导致抛出“错误:原因:无法找到请求目标的有效证书路径”。
创始人
2024-08-15 22:30:15
0

当使用Android Studio进行网络请求时,有时会遇到服务器证书过期的问题,导致抛出“错误:原因:无法找到请求目标的有效证书路径”的异常。以下是一种解决方法,其中包含了代码示例。

解决方法:

  1. 创建一个自定义的SSLSocketFactory类,用于处理证书验证的问题。在该类中,我们可以重新实现验证服务器证书的逻辑。
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class CustomSSLSocketFactory {
    public static void disableCertificateValidation() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
                        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
                    }
            };

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }
}
  1. 在进行网络请求之前,调用CustomSSLSocketFactory类的disableCertificateValidation()方法,禁用证书验证。
CustomSSLSocketFactory.disableCertificateValidation();

// 进行网络请求的代码示例
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
...

通过以上方法,我们可以禁用Android Studio对服务器证书的验证,从而解决"错误:原因:无法找到请求目标的有效证书路径"异常。请注意,禁用证书验证存在安全风险,请在安全可靠的环境中使用。

相关内容

热门资讯

透视存在"哈糖大菠萝... 1、透视存在"哈糖大菠萝可以开挂吗"详细辅助力荐教程(买脚本靠谱教程)2、进入游戏-大厅左侧-新手福...
透视计算"智星德州插... 《透视计算"智星德州插件2024最新版"详细辅助新2025版(可以破解游戏教程)》 智星德州插件20...
透视了解"xpoke... 透视了解"xpoker辅助器"详细辅助透牌教程(有机器人教程);1.xpoker辅助器 ai辅助创建...
透视好友房"wepo... 透视好友房"wepoker模拟器哪个"详细辅助2025新版总结(可以开辅助神器);建议优先通过wep...
透视玄学"wpk透视... 透视玄学"wpk透视插件"详细辅助专业教程(买脚本靠谱透明)关于wpk透视插件机制的,其中提到了后台...
透视辅助"aapok... 透视辅助"aapoker怎么选牌"详细辅助插件教程(私人局有透视攻略)关于aapoker怎么选牌机制...
透视实锤"wepok... 透视实锤"wepoker私人局辅助挂"详细辅助透牌教程(可以下载游戏攻略);大神普及一款德州ai内幕...
透视ai"poker... 透视ai"pokermaster脚本"详细辅助软件教程(私人局辅助挂辅助);实战中需综合运用上述技巧...
透视ai"德州局hh... 透视ai"德州局hhpoker"详细辅助靠谱教程(手机版透视脚本神器);《WPK辅助透视》‌:支持手...
透视能赢"wepok... 透视能赢"wepoker透视脚本免费app"详细辅助技巧教程(透视脚本免费透明);人气非常高,ai更...