Yadvendra
Yadvendra

Reputation: 27

Check if url exists JAVA


I'm trying to check if the url entered by the user actually exists. Below is what I have tried.

public static Boolean checkURLExists(String urlName) 
{
    Boolean urlCheck=false;
    try{
        URL url = new URL(urlName);
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("GET");
        int responseCode = huc.getResponseCode();
        String responseMessage = huc.getResponseMessage();
        char a=String.valueOf(Math.abs((long)huc.getResponseCode())).charAt(0);
        if ((a == '2' || a == '3')&& (responseMessage.equalsIgnoreCase("ok")||responseMessage.equalsIgnoreCase("found")||responseMessage.equalsIgnoreCase("redirect"))) {
            System.out.println("GOOD "+responseCode+" - "+a);
            urlCheck=true;
        } else {
            System.out.println("BAD "+responseCode+" - "+a);
        }
    }catch(Exception e){
                    e.printStackTrace();
    }
    return urlCheck;
}

The issue with the above code is that it returns http://www.gmail.com or http://www.yahoo.co.in etc. as invalid URLs with response code 301 & response message "Moved permanently" but they actually redirects to other url, Is there any way to detect that the url when entered in browser will open a page?

Thank you.

Upvotes: 1

Views: 1271

Answers (1)

Stephen C
Stephen C

Reputation: 718678

Well the normal behavior of a web browser when it sees a 301 response is to follow the redirect. But you seem to have told your test code NOT to do that. If you want your code to behave (more) like a browser would, change this

  HttpURLConnection.setFollowRedirects(false);

to this

  HttpURLConnection.setFollowRedirects(true);

Upvotes: 1

Related Questions