【问题标题】:InetAddress.getAllByName() throws UnknownHostExceptionInetAddress.getAllByName() 抛出 UnknownHostException
【发布时间】:2017-04-25 04:32:55
【问题描述】:

为了让我的应用获得 Apple 审核团队的批准,我遇到了另一个障碍。

正如标题所示,当调用InetAddress.getAllByName("https://artatlas.io") 时会抛出UnknownHostException。这只发生在他们的测试过程中。当我在本地 NAT64 网络上测试我的应用程序时(按照 Apple 的建议);该错误永远不会发生,并且该应用程序按预期工作。

我正在运行的代码:

System.setProperty("java.net.preferIPv6Addresses", "true");
System.setProperty("networkaddress.cache.negative.ttl", "0");
InetAddress[] addrs;

try {
    addrs = InetAddress.getAllByName("https://artatlas.io");
    String addresses = "";
    for(InetAddress addr: addrs){
        addresses += addr + "\n";
    }
    System.out.println("Addresses: " + addresses + "\n");
} catch (IOException e1) {
    e1.printStackTrace();
}

我发现,我附加“https://”的任何内容似乎都返回相同的单个 IP 地址:

Addresses: https://artatlas.io/122.150.5.20
Addresses: https://google.com/122.150.5.20
Addresses: https://www.google.com/122.150.5.20

我可以摆脱 https,但我担心以后使用 HttpsURLConnection 会失败(我的连接必须是 https)

testUrl = new URL("https://artatlas.io");
testConn = (HttpsURLConnection) testUrl.openConnection();

我知道HttpsURLConnection 使用 InetAddress 实例来形成其连接,所以问题是它使用什么过程来解析 URL 字符串,它是否删除了协议?这里的正确方法是什么?

【问题讨论】:

    标签: java ios eclipse oracle-maf


    【解决方案1】:

    主机名不应包含协议。无论您打算使用什么协议,主机都是相同的。不管后面的HTTPS连接失败与否,InetAddress.getAllByName()都与它无关(它不也不能保证成功或失败)。

    此时您只处理 DNS,所以它只是 foo.com123.45.67.89 或 IPv6 地址。

    【讨论】:

    • 分离主机名和协议对我来说是一个重要的实现,谢谢。那么可以安全地假设当我创建一个 HttpsURLConnection 并向它传递一个包含协议的 URL 时,它不会反过来失败(因为 Java 在构造 InetAddress 对象时知道不包含协议)?
    • 当然。 URL 与主机名不同。使用 URL,您需要提供协议。没有任何假设。
    • 感谢您的解释,这很有意义。我已经接受了这个作为答案,我也会投票给你,但我似乎有点缺乏互联网积分!
    • 别担心,我想我已经足够了:)
    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2018-06-20
    • 2017-07-23
    • 2011-02-23
    • 2019-05-01
    相关资源
    最近更新 更多