我可以检查URL上是否存在文件?

时间:2010-03-17 11:42:05

标签: java http

can I check if a file exists at a URL?

这个链接非常适合C#,java怎么样。我搜索但我没有找到好的解决方案。

2 个答案:

答案 0 :(得分:10)

它在Java中非常相似。您只需要评估HTTP响应代码:

final URL url = new URL("http://some.where/file.html");
url.openConnection().getResponseCode();

可以找到更完整的示例here

答案 1 :(得分:4)

提供更易于复制和粘贴的干净版本。

try {
    final URL url = new URL("http://your/url");
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    int responseCode = huc.getResponseCode();
    // Handle response code here...
} catch (UnknownHostException uhe) {
    // Handle exceptions as necessary
} catch (FileNotFoundException fnfe) {
    // Handle exceptions as necessary
} catch (Exception e) {
    // Handle exceptions as necessary
}