使用 URL 检查远程服务器上是否存在文件
如何在 Java 中检查文件是否存在于远程服务器(由 HTTP 提供服务)上并具有其 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
唯一正确的方法是下载它:)。在某些服务器上,通常您可以通过对同一 url 发出 HEAD 请求(而不是 GET 请求)来逃脱。这将仅返回资源元数据,而不返回实际的文件内容。
更新:检查 org.life.java 的答案,了解如何执行此操作的实际技术细节。
The only true way is to download it :). On some servers usually you can get away by issuing a HEAD request insted of a GET request for the same url. This will return you only the resource metadata and not the actual file content.
Update: Check org.life.java's answer for the actual technical details on how to do this.
与其建立 URLConnection。如果你成功了,它就存在。您可能必须打开它的输入流,但您不必阅读内容。您可以立即关闭流。
Make a URLConnection to it. If you succeed, it exists. You may have to go so far as opening an input stream to it, but you don't have to read the contents. You can immediately close the stream.
如果到 URL 的连接(使用 HttpURLConnection) 返回 HTTP 状态代码 200 则文件存在。
编辑:请注意,由于我们只关心它是否存在,因此无需请求整个文档。我们可以使用 HTTP HEAD 请求方法来请求标头来检查它是否存在。
来源:http://www.rgagnon.com/javadetails/java-0059.html
If the connection to a URL (made with HttpURLConnection) returns with HTTP status code 200 then the file exists.
EDIT: 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.
Source: http://www.rgagnon.com/javadetails/java-0059.html
检查 URL 是否存在
Checking if a URL exists or not
检查这个,它对我有用。源 URL:检查服务器上是否存在 URL
Check this, it works for me. Source URL: Check if URL exists or not on Server
假设文件是通过 http 提供的,您可以向 URL 发送 HEAD 请求并检查返回的 http 响应代码。
Assuming the file is being served through http, you can send a HEAD request to the URL and check the http response code returned.