首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用Java检查URL是否存在或返回404?

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

Stack Overflow用户
提问于 2009-09-04 09:38:51
回答 5查看 139.4K关注 0票数 76
代码语言:javascript
复制
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");
}

这应该会打印出来

代码语言:javascript
复制
exists
does not exists

测试

代码语言:javascript
复制
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

代码语言:javascript
复制
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)");
EN

回答 5

Stack Overflow用户

发布于 2009-09-04 11:14:07

您可能想要添加

代码语言:javascript
复制
HttpURLConnection.setFollowRedirects(false);
// note : or
//        huc.setInstanceFollowRedirects(false)

如果您不想遵循重定向(3XX)

你只需要一个“头”,而不是"GET“。

代码语言:javascript
复制
huc.setRequestMethod("HEAD");
return (huc.getResponseCode() == HttpURLConnection.HTTP_OK);
票数 60
EN

Stack Overflow用户

发布于 2011-04-22 01:39:41

这对我很有效:

代码语言:javascript
复制
URL u = new URL ( "http://www.example.com/");
HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection (); 
huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD"); 
huc.connect () ; 
int code = huc.getResponseCode() ;
System.out.println(code);

感谢上面的建议。

票数 44
EN

Stack Overflow用户

发布于 2009-09-04 09:40:09

通过在URL对象上调用openConnection()来使用HttpUrlConnection

一旦你从连接中读取,getResponseCode()就会给你超文本传输协议响应。

例如:

代码语言:javascript
复制
   URL u = new URL("http://www.example.com/"); 
   HttpURLConnection huc = (HttpURLConnection)u.openConnection(); 
   huc.setRequestMethod("GET"); 
   huc.connect() ; 
   OutputStream os = huc.getOutputStream(); 
   int code = huc.getResponseCode(); 

(未测试)

票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1378199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档