views:

280

answers:

2

I already read the link checker question posted in SO. If there are more questions of this kind and I missed them, my apologies.

We need to find broken links in a website in a very easy way and scriptable way, so we can document the links that are broken. I found a blog post with some code written in java that will do exactly what I need, and my very basic knowledge let me compile it, but I get errors every time. I thought that maybe someone here might be able to direct me to why the code does not compile.

Here is the code:

import java.net.HttpURLConnection;
import java.net.URL;
class links
{

private static boolean isLive(String link) {
    HttpURLConnection urlConnection = null;
    try {
      URL url = new URL(link);
      urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestMethod("HEAD");
      urlConnection.connect();
      String redirectLink = urlConnection.getHeaderField("Location");
      if (redirectLink != null && !url.equals(redirectLink)) {
        return isLive(redirectLink);
      } else {
        return urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK;
      }
    } catch (Exception e) {
      return false;
    } finally {
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
    }
  }

  public static void main(String[] args) {
    System.out.println(isLive("http://www.fakelink.net"));
  }
}

Thanks to all that reply. I putting the code that compiles here, for future reference.

A: 

The code seems correct. May be you have not imported the required Packages. It will help if you could post the compiler errors that you are getting.

Deepak Singh Rawat
thanks very much. I will do that early in the morning. Thanks.
Geo
+1  A: 

You need to have the proper packages imported. In this case, you should have the follow at the top of the file:

import java.net.HttpURLConnection;
import java.net.URL;

I'm also getting a compiler warning on the following piece of code:

 && !url.equals(redirectLink)

It's trying to equate url (which is a URL) to redirectLink (which is a String). In Java it will automatically compare the string value when this happens and the toString actually gives what you want. To be more precise in the authors code I would change the above code to:

 && !url.toExternalForm().equals(redirectLink)

Note: In netbeans, you can simply right click and select the option Fix Imports (or hit Ctrl + Shift + I) and it will try to find the correct packages that you're currently using and automatically insert the import statements.

Kevin M.