使用其 URL 检查远程服务器上是否存在文件 [英] Check if file exists on remote server using its URL

查看:50
本文介绍了使用其 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

这篇关于使用其 URL 检查远程服务器上是否存在文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆