Friday, January 01, 2010

Check URL Exists or not In Java

In order to check that url exsists or not, you need to do following.
  • Create instance of URL
  • Open connection to url using url.openConnection
  • Create instance of HttpURLConnection
  • Check that httpURLConnection.getResponseCode() is equal to 200 or not.

Java Program to check provided URL exists or not :
package com.anuj.network;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

public class URLExists {

    public static void main(String s[]) {
        String urlName = "http://www.google.com/a.html";
        URLExists uRLExists = new URLExists();
        uRLExists.checkURLExists(urlName);
    }

    public void checkURLExists(String URLName) {
        try {
            URL url = new URL(URLName);
            URLConnection urlConnection = url.openConnection();

            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            httpURLConnection.setRequestMethod("HEAD");

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                System.out.println("URL Exist");
            } else {
                System.out.println("URL not Exists");
            }
        } 
        catch(UnknownHostException unknownHostException){
            System.out.println("UnkownHost");
            System.out.println(unknownHostException);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
Please note that if you are working under proxy then you need to write code to set proxy before using above program.

Output :
URL not Exists
BUILD SUCCESSFUL (total time: 5 seconds) 

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment