Clone
Clone

Reputation: 3648

How can you quickly validate that a provided URL is valid?

I am writing a program where a user can input a URL but I need to check if it,s a real URL and not just some random string like abcdefg.gggg. I am thinking about pinging the URL. What is the fastest way of doing that in java?

I am thinking something like this but would be happy if you have a faster alternative:

HttpURLConnection connection = null;
try {
    URL u = new URL(urlstring);
    connection = (HttpURLConnection) u.openConnection();
    connection.setRequestMethod("HEAD");
    int code = connection.getResponseCode();
    System.out.println("" + code);
    if (code == 200) {
        ok = true;
    }
} catch (Exception error) {
    // error
}

Upvotes: 0

Views: 2066

Answers (2)

TriS
TriS

Reputation: 4038

Any provided URL can be validated in multiple ways. The key points to be kept in mind are

  • Valid Url Syntax
  • Url connectivity exists

a. Url Syntax validation

  1. The syntax can be validated by using commons-validator
public boolean isValidURL(String url) throws MalformedURLException {
    UrlValidator urlValidator = new UrlValidator();
    return validator.isValid(url);
}
  1. Using JDK to validate the url. As it tries to create the URL, but fails if its invalid.
Public boolean isValidURL(String url) throws MalformedURLException, URISyntaxException {
    try {
        new URL(url).toURI();
        return true;
    } catch (MalformedURLException e | URISyntaxException e) {
        return false;
    }
}
  1. Using Regular Expression ( You should customize the expression as per your requirement)
    private static final String URL_REGEX =
            "^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))" +
            "(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)" +
            "([).!';/?:,][[:blank:]])?$";
 
    private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
 
    public static boolean urlValidator(String url)
    {
        if (url == null) {
            return false;
        }
 
        Matcher matcher = URL_PATTERN.matcher(url);
        return matcher.matches();
    }

b. Connectivity validation

  1. Using GET Request and validating response.
 public static String getStatus(String url) throws IOException {
 
        String result = "";
        try {
            URL urlObj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(3000);
            con.connect();
 
            int code = con.getResponseCode();
            if (code == 200) {
                result = "On";
            }
        } catch (Exception e) {
            result = "Off";
        }
        return result;
    }
  1. Using http HEAD request method that is identical to GET except that it does not return the response body
URL url = new URL(url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
  1. Fetch IP Address of any url ( not recommended for ping validation as it has few issues)
InetAddress ipAddress = InetAddress.getByName(new URL(url).getHost());

Upvotes: 3

Sohaib Ahmed
Sohaib Ahmed

Reputation: 3062

Check url is valid or not by Patterns built-in class

boolean isUrlValid = Patterns.WEB_URL.matcher(urlstring).matches();
if (!isUrlValid) {
    Toast.makeText(this, "Invalid Url", Toast.LENGTH_SHORT).show();
    return;
}

Upvotes: 0

Related Questions