java - 如何检查 URL 是否存在或使用 Java 返回 404?

标签 java url http-status-code-404

String urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_001.pdf";
URL url = new URL(urlString);
if(/* Url does not return 404 */) {
    System.out.println("exists");
} else {
    System.out.println("does not exists");
}
urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_190.pdf";
url = new URL(urlString);
if(/* Url does not return 404 */) {
    System.out.println("exists");
} else {
    System.out.println("does not exists");
}

这应该打印出来

exists
does not exists

测试

public static String URL = "http://www.nbc.com/Heroes/novels/downloads/";

public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
    URL u = new URL(urlString); 
    HttpURLConnection huc =  (HttpURLConnection)  u.openConnection(); 
    huc.setRequestMethod("GET"); 
    huc.connect(); 
    return huc.getResponseCode();
}

System.out.println(getResponseCode(URL + "Heroes_novel_001.pdf")); 
System.out.println(getResponseCode(URL + "Heroes_novel_190.pdf"));   
System.out.println(getResponseCode("http://www.example.com")); 
System.out.println(getResponseCode("http://www.example.com/junk"));           

输出

200
200
200
404

解决方案

在 .connect() 之前添加下一行,输出将为 200、404、200、404

huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");

最佳答案

你可能想添加

HttpURLConnection.setFollowRedirects(false);
// note : or
//        huc.setInstanceFollowRedirects(false)

如果你不想跟随重定向 (3XX)

您只需要一个“HEAD”而不是“GET”。

huc.setRequestMethod("HEAD");
return (huc.getResponseCode() == HttpURLConnection.HTTP_OK);

关于java - 如何检查 URL 是否存在或使用 Java 返回 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1378199/

相关文章:

java - 如何处理一个流畅的界面,其中每个步骤都可以是终端操作?

java - 如何将 Android Studio 项目推送到远程 GitLab 存储库

java - 从 odesign Sirius 文件导出图表/节点

python - 从 URL 字符串中解析站点/域名

apache - 考虑到 SEO 升级网站

部署到 Azure 的 node.js 网站 - 404 无法加载 .json 资源

java - Saxon 9.6.0.7版本也需要saxon-dom?

objective-c - NSThread 中的 NSUrlConnection - 没有执行委托(delegate)!

regex - mod重写url中的路径

ruby-on-rails - 在所有载波上传的图像上未找到生产中的载波 404