63

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.

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
Rui
  • 5,900
  • 10
  • 38
  • 56

6 Answers6

103
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

Adam
  • 43,763
  • 16
  • 104
  • 144
  • do we have to configure the lines mentioned in note (commented lines) ? – Sangram Anand May 04 '12 at 19:21
  • 3
    I wanna mention this: The server needs to be handling HEAD requests in order for this to work. – imdahmd Mar 17 '13 at 13:00
  • 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? – Niko Apr 15 '14 at 07:56
  • This is a usefull link explaning HEAD method uses: https://ochronus.com/http-head-request-good-uses/ – edrian Aug 19 '15 at 15:56
  • @imdhmd But one should not disable the head request as explained here->http://security.stackexchange.com/questions/62811/should-i-disable-http-head-requests – Hirdesh Vishwdewa Nov 05 '15 at 08:04
  • You should call con.disconnect() in a "finally" block... – JM Lord Nov 24 '15 at 13:52
  • some url will return 403 forbidden for HEAD request while 200 OK for get request. For example http://ia.media-imdb.com/images/M/MV5BMTQ3MDQwMjQ5NV5BMl5BanBnXkFtZTgwMTY2MjAyOTE@._V1_UY1200_CR69,0,630,1200_AL_.jpg – jiawen Jul 12 '16 at 04:51
  • Why should you call "HttpURLConnection.setFollowRedirects(false);" ? – The incredible Jan Mar 24 '17 at 13:19
16
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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
6

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();
            }                  
    }           
}
}
Community
  • 1
  • 1
Ishtiyaq Husain
  • 434
  • 4
  • 11
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.

Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46
3

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.

Mihai Toader
  • 12,041
  • 1
  • 29
  • 33
0

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.

rfeak
  • 8,124
  • 29
  • 28