java - java中的URL非法参数异常

标签 java url

我有一个 URL http://boss.blogs.nytimes.com/2014/07/10/today-in-small-business-pizza-for-everyone/我想测试这个 URL 是否可以在 java 中访问(即我想 ping URL)。此 URL 在网络浏览器中正常工作。

我也有下面的代码

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

最佳答案

您正在检查的页面返回 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;
        }
    } 

关于java - java中的URL非法参数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24799068/

相关文章:

javascript - 安全错误 : The operation is insecure - window. history.pushState()

linux - 是否可以使用 Linux 命令从 HTTP 服务器读取前 N 个字节?

javascript - 结合 Bookmarklet 来创建 HTTP 和 HTTPS 之间的切换?

java - 将 3rd-party jar 部署到 clojars?

java - 如何在 Gradle 中共享通用测试依赖版本?

java - 如何在java中获取浏览器的javascript控制台输出?

java - 获取URL内容

java.lang.IllegalArgumentException : Illegal character in path at index 33: https://box. one.th/app/api/上传

java - 使用 IText 库进行 PDF 签名

java - hibernate中的Session、Connection对象到底是什么