Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check format of URL

Tags:

java

I need a Java code which accepts an URL like http://www.example.com and displays whether the format of URL is correct or not.

like image 340
Ram Avatar asked Nov 29 '22 18:11

Ram


2 Answers

Based on the answer from @adarshr I would say it is best to use the URL class instead of the URI class, the reason for it being that the URL class will mark something like htt://example.com as invalid, while URI class will not (which I think was the goal of the question).

//if urlStr is htt://example.com return value will be false
public boolean isValidURL(String urlStr) {
    try {
      URL url = new URL(urlStr);
      return true;
    }
    catch (MalformedURLException e) {
        return false;
    }
}
like image 28
Ruben Estrada Avatar answered Dec 01 '22 09:12

Ruben Estrada


This should do what you're asking for.

public boolean isValidURL(String urlStr) {
    try {
      URL url = new URL(urlStr);
      return true;
    }
    catch (MalformedURLException e) {
        return false;
    }
}

Here's an alternate version:

public boolean isValidURI(String uriStr) {
    try {
      URI uri = new URI(uriStr);
      return true;
    }
    catch (URISyntaxException e) {
        return false;
    }
}
like image 77
adarshr Avatar answered Dec 01 '22 09:12

adarshr