Check if file exists on remote server using its URL

77,423

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

Assuming the file is being served through http, you can send a HEAD request to the URL and check the http response code returned.

Solution 5

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.

Share:
77,423
Rui
Author by

Rui

Updated on November 03, 2020

Comments

  • Rui
    Rui over 3 years

    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.

  • Sangram Anand
    Sangram Anand about 12 years
    do we have to configure the lines mentioned in note (commented lines) ?
  • imdahmd
    imdahmd about 11 years
    I wanna mention this: The server needs to be handling HEAD requests in order for this to work.
  • Martin Serrano
    Martin Serrano over 10 years
    InputStream implementations may not necessarily do a read on the server side so it may still not exist.
  • Niko
    Niko about 10 years
    when I have a special char like 'Ü' in the filename, and parse it with URLEncoder.encode(filename, "UTF-8"), it tells me that the file does not exist?
  • edrian
    edrian over 8 years
    This is a usefull link explaning HEAD method uses: ochronus.com/http-head-request-good-uses
  • Hirdesh Vishwdewa
    Hirdesh Vishwdewa over 8 years
    @imdhmd But one should not disable the head request as explained here->security.stackexchange.com/questions/62811/…
  • JM Lord
    JM Lord over 8 years
    You should call con.disconnect() in a "finally" block...
  • Matej Kormuth
    Matej Kormuth over 8 years
    This is Android related solution. OP didn't asked for Android solution.
  • jiawen
    jiawen almost 8 years
    some url will return 403 forbidden for HEAD request while 200 OK for get request. For example ia.media-imdb.com/images/M/…
  • The incredible Jan
    The incredible Jan about 7 years
    Why should you call "HttpURLConnection.setFollowRedirects(false);" ?