java中的URL非法参数异常

时间:2014-07-17 08:57:54

标签: java url

我有一个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。我不知道为什么会发生这种情况,如何验证该主机是否可以访问?

1 个答案:

答案 0 :(得分: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;
        }
    }