1

URL comes from form in Play Framework 2. I would like to check whether URL really exists.

So it seems like it could be done via combining two approached.

Is there a built-in similar functionality using annotation in model?

How to create a custom validator in Play Framework 2.0?

How to check if a URL exists or returns 404 with Java?

EDIT: for bounty you can provide implementation of URL validator (not build-in).

Community
  • 1
  • 1
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101

1 Answers1

4

Basically you need to perform an HTTP HEAD request for the target URL and check if you got an acceptable response code. Acceptable response code might be OK (200), temporarily moved (???) and other codes that will lead to the page if not right now at least very soon.

Why HEAD? Because GET will download the whole page and HEAD will download only the HTTP header. This will take less time and time is not a friend in this case. The validation should be done very quickly, and making an HTTP request takes time. During those couple seconds (or more, depending on server and network load) the user will wonder what's happening and get frustrated. Unless you can show one of those animated progress indicators to let him know validating its input takes some time.

You should do this like those password strength validators where the value is validated in a background AJAX call once the focus leaves the input control and there's an animated indicator on the side where the result will be shown. In the meantime the user can fill out other information.

The code would something like this:

public class UrlExistenceValidator ... {
    public boolean isValid(Object object) {
        if (!(object instanceof String)) {
            return false;
        }

        final String urlString = (String) object;

        final URL url = new URL(urlString);
        final HttpURLConnection huc =  (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        huc.connect();

        final int code = huc.getResponseCode();
        return code != 404;
    }
}
Cebence
  • 2,406
  • 2
  • 19
  • 20