gpt4 book ai didi

java - Android 主机名未得到验证。如何允许所有主机?

转载 作者:太空宇宙 更新时间:2023-11-04 14:24:21 26 4
gpt4 key购买 nike

我正在尝试从以 HTTPS 开头的 URL 获取图像。我不断收到主机名未验证的异常。

我看了一下这个问题java.io.IOException: Hostname was not verified但不明白如何让它发挥作用。

有什么办法可以允许所有主机名吗?

这是给我带来麻烦的代码:

public Drawable drawableFromUrl(String url) {
Bitmap x;
HttpURLConnection connection;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
return null;
}
return null;
}

预先感谢您的帮助

最佳答案

当 TLS 证书是自签名的或证书上的域与服务器的主机名不匹配时,会出现此错误。

This answer 提供了完整的解决方案:

/**
* Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
* aid testing on a local box, not for use on production.
*/
private static void disableSSLCertificateChecking() {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {

@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
// not implemented
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
// not implemented
}

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

}
};

try {

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}

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

} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}

在建立第一个 HTTPS 连接之前,只需随时运行一次即可。但是,如果您控制服务器,则强烈建议您尝试获取有效的证书。

关于java - Android 主机名未得到验证。如何允许所有主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com