Java中的URL非法参数异常

4
我有一个URL:http://boss.blogs.nytimes.com/2014/07/10/today-in-small-business-pizza-for-everyone/,我想在Java中测试这个URL是否可达(即我想ping这个URL)。这个URL在Web浏览器中正常工作。
我也有以下代码。
  public boolean isReachable(String url) {
    if (url == null)
        return false;
    try {
        URL u = new URL(url);
        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        huc.setRequestMethod("GET");
        huc.setReadTimeout(readTimeOut);
        huc.connect();
        int code = 0;
        if (u.getHost() != null)
            code = huc.getResponseCode();   
        huc.disconnect();
        return (200 <= code && code <= 399);
    }catch(Exception ee) {
        System.out.println(ee);
        return false;
    }

当我执行这段代码时,我遇到了java.lang.IllegalArgumentException: protocol = http host = null的错误。我不知道为什么会出现这种情况,我该如何验证这个主机是否可达?

你调试过这段代码并在URL构造函数调用之前验证了url的值吗? - JamesB
System.out.print(u.getHost()); 上你会得到什么? - Am_I_Helpful
3
setFollowRedirects(false) 特别是当 302 = REDIRECT 处于接受范围时,可以使代码更快,并限制错误搜索区域。尝试访问 http://blogs.nytimes.com/ 及其子域名等网址时,可能需要使用类似 User-Agent: ... 的浏览器头信息来伪装成浏览器。 - Joop Eggen
是的,我已经调试过了,url的值是正确的。当我打印它时,它显示为boss.blogs.nytimes.com(u.getHost())。 - user1858712
但是,Joop Eggen,我想要验证这个绝对URL。 - user1858712
1个回答

4
您正在检查的页面返回了303代码,这意味着将发生重定向。将setInstanceFollowRedirects(false)添加到您的HttpURLConnection实例中应该可以解决问题。
您的代码应该如下所示:
    public boolean isReachable(String url) {
       if (url == null)
           return false;
       try {
        URL u = new URL(url);
        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
        // HttpURLConnection.setFollowRedirects(true); REMOVE THIS LINE
        huc.setRequestMethod("GET");
        huc.setReadTimeout(readTimeOut);
        huc.setInstanceFollowRedirects(false); // ADD THIS LINE
        huc.connect();
        int code = 0;
        if (u.getHost() != null)
            code = huc.getResponseCode();   
        huc.disconnect();
        return (200 <= code && code <= 399);
        }catch(Exception ee) {
        System.out.println(ee);
        return false;
        }
    } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接