Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists on remote server using its URL [duplicate]

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.

like image 403
Rui Avatar asked Jan 04 '11 17:01

Rui


1 Answers

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

like image 126
Adam Avatar answered Oct 12 '22 23:10

Adam