gpt4 book ai didi

android - 使用 HttpURLConnection 和 HttpsURLConnection 连接到 https?

转载 作者:IT老高 更新时间:2023-10-28 22:10:02 27 4
gpt4 key购买 nike

如果我尝试使用 HttpURLConnectionHttpsURLConnection 连接到“https”有什么区别?

我能够同时使用 HttpURLConnectionHttpsURLConnection 连接到“https”,所以我很困惑。我以为只有使用 HttpsURLConnection?

才能建立到“https”的连接

以下是我的一些问题:

  • 如果我能够使用 HttpURLConnection 打开到“https”的连接,我的连接是仍然在“https”还是变成“http”?
  • 如何验证证书?由于在连接到“https”时我的 HttpURLConnection 上没有任何 SSLSocketFactoryHostnameVerifier,所以 SSLSocketFactory我在使用 HostnameVerifier 吗?
  • 这是否意味着无论证书是否受信任,我都信任一切?

最佳答案

  1. 正在使用 HTTPS 连接。
  2. 默认行为
  3. 不确定,但请阅读下文。

我只是写了一些代码作为测试(见下文)。最终发生的是 URL.openConnection() 调用将返回一个 libcore.net.http.HttpsURLConnectionImpl 类。

这是 HttpsURLConnection 的实现,但 HttpsURLConnection 继承自 HttpURLConnection。所以你看到了多态性在起作用。

进一步查看调试器,似乎该类正在使用默认工厂方法。

主机名验证器 = javax.net.ssl.DefaultHostnameVerifier

sslSocketFactory = org.apache.harmony.xnet.provider.jsse.OpenSSLSocketFactoryImpl

基于此,似乎正在使用默认行为。我不知道这是否意味着如果您信任一切,但您肯定是在建立 HTTPS 连接。

文档有点暗示连接将自动信任众所周知但非自签名的 CA。 (见下文)我没有对此进行测试,但他们在 how to accomplish that here 上有示例代码.

If an application wants to trust Certificate Authority (CA) certificates that are not part of the system, it should specify its own X509TrustManager via a SSLSocketFactory set on the HttpsURLConnection.

Runnable r = new Runnable() {

public void run() {
try {
URL test = new URL("https://www.google.com/");
HttpURLConnection connection = (HttpURLConnection) test.openConnection();
InputStream is = connection.getInputStream();
StringWriter sw = new StringWriter();
String value = new java.util.Scanner(is).useDelimiter("\\A").next();
Log.w("GOOGLE", value);
} catch(Exception e) {
Log.e("Test", e.getMessage());
}
}

};

Thread t = new Thread(r);
t.start();

关于android - 使用 HttpURLConnection 和 HttpsURLConnection 连接到 https?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9960998/

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