使用URL检查远程服务器上是否存在文件 [英] Check if file exists on remote server using its URL
问题描述
如果远程服务器(由HTTP提供服务)上存在文件,如果有URL,我如何检查Java?我不想下载文件,只检查它的存在。
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
这篇关于使用URL检查远程服务器上是否存在文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!