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

发布于 2024-10-10 15:30:32 字数 73 浏览 5 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

救赎№ 2024-10-17 15:30:34

唯一正确的方法是下载它:)。在某些服务器上,通常您可以通过对同一 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.

帅冕 2024-10-17 15:30:34

与其建立 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.

神经大条 2024-10-17 15:30:33
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 则文件存在。

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

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

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;
    }
  }

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

℡Ms空城旧梦 2024-10-17 15:30:33
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 是否存在

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;
    }
  }  

Checking if a URL exists or not

夏九 2024-10-17 15:30:33

检查这个,它对我有用。源 URL:检查服务器上是否存在 URL

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     

    String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";

    MyTask task = new MyTask();
    task.execute(customURL);
}


private class MyTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(String... params) {

         try {
                HttpURLConnection.setFollowRedirects(false);
                HttpURLConnection con =  (HttpURLConnection) new URL(params[0]).openConnection();
                con.setRequestMethod("HEAD");
                System.out.println(con.getResponseCode()); 
                return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
            }
            catch (Exception e) {   
                e.printStackTrace();    
                return false;
            }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        boolean bResponse = result;
         if (bResponse==true)
            {
                Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();      
            }
            else
            {           
                Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
            }                  
    }           
}
}

Check this, it works for me. Source URL: Check if URL exists or not on Server

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     

    String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";

    MyTask task = new MyTask();
    task.execute(customURL);
}


private class MyTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(String... params) {

         try {
                HttpURLConnection.setFollowRedirects(false);
                HttpURLConnection con =  (HttpURLConnection) new URL(params[0]).openConnection();
                con.setRequestMethod("HEAD");
                System.out.println(con.getResponseCode()); 
                return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
            }
            catch (Exception e) {   
                e.printStackTrace();    
                return false;
            }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        boolean bResponse = result;
         if (bResponse==true)
            {
                Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();      
            }
            else
            {           
                Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
            }                  
    }           
}
}
池予 2024-10-17 15:30:33

假设文件是​​通过 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文