gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:44:59 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com