4

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.

Peter Lang
  • 54,264
  • 27
  • 148
  • 161
Ram
  • 406
  • 3
  • 5
  • 14

2 Answers2

22

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;
    }
}
adarshr
  • 61,315
  • 23
  • 138
  • 167
  • 1
    use the [java.net.URI](http://download.oracle.com/javase/6/docs/api/java/net/URI.html) class instead. – McDowell Apr 27 '11 at 11:07
  • no guys it did not worked out can you please provide full code – Ram Apr 27 '11 at 15:39
  • 1
    @user what didn't work? YOU provide your code and show us what you have done so far. – adarshr Apr 27 '11 at 16:23
  • @adarshr Ok.I understand URL is a subset of URI but in context of this question why did you use URI as well? Won't URL be more specific? – Suvarna Pattayil Mar 17 '15 at 09:03
  • 1
    @Suvarna there's no particular reason. It is just a matter of taste. I was just demonstrating two different ways of solving the same problem. – adarshr Mar 17 '15 at 10:03
  • 1
    The "url" or "uri" local variable is not necessary. – Mark W Aug 23 '17 at 07:36
  • never use exception in nomral program flow. let thwor the exception is bad – dermoritz Dec 06 '19 at 08:49
  • According to version 1 (`URL`) "stackoverflow.com" is invalid, according to version 2 (`URI`) even nonsense like "---" is valid, so both versions aren't exactly great (unless you have to set up some type of pattern first?). I'd recommend using [Regex](https://stackoverflow.com/a/58578580/2016165) or Apache's [URLValidator](https://stackoverflow.com/a/5078838/2016165) instead. – Neph Mar 17 '20 at 14:18
1

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;
    }
}
Ruben Estrada
  • 338
  • 1
  • 7