You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在InetAddress.getAllByName中传入URL?解决UnknownHostException异常

问题解决:传入带协议的URL导致UnknownHostException

InetAddress.getAllByName()只认纯主机名(比如google.com)或IP地址,你传的https://google.com带了协议前缀,会被当成完整主机名去解析,自然找不到对应的主机,所以抛出异常。

解决办法分两种:

  • 简单版:直接去掉https://前缀,传入google.com即可
  • 通用适配版:用Java的URL类解析完整URL,自动提取主机名,适合处理各种带协议的URL(比如http、https、ftp等)

通用版代码示例:

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws Exception {
        String urlStr = "https://google.com";
        URL url = new URL(urlStr);
        // 提取URL中的主机名
        String host = url.getHost();
        
        InetAddress[] inetAddresses = InetAddress.getAllByName(host);
        for (InetAddress addr : inetAddresses) {
            System.out.println(addr.getHostAddress());
        }
    }
}

这样不管你传入的是带https://、http://还是其他协议前缀的URL,都能正确提取主机名并解析对应的IP地址。

内容的提问来源于stack exchange,提问作者therepanic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:44:52