使用其 URL 检查远程服务器上是否存在文件

问题描述:

如果远程服务器(由 HTTP 提供服务)上存在一个文件,我如何在 Java 中检查它的 URL?我不想下载文件,只是检查它是否存在.

How can I check in Java if a file exists on a remote server (served by HTTP), having its URL? I don't want to download the file, just check its existence.

import java.net.*;
import java.io.*;

public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      //        HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
  }

如果连接到一个 URL (使用 HttpURLConnection) 返回 HTTP 状态代码 200 然后文件存在.

If the connection to a URL (made with HttpURLConnection) returns with HTTP status code 200 then the file exists.

请注意,由于我们只关心它是否存在,因此不需要请求整个文档.我们可以使用 HTTP HEAD 请求方法请求标头以检查它是否存在.

Note that since we only care it exists or not there is no need to request the entire document. We can just request the header using the HTTP HEAD request method to check if it exists.

来源:http://www.rgagnon.com/javadetails/java-0059.html