开发者

Check format of URL

I need a Java code which accepts an URL like http://www.example.com and displays whether the format of URL is cor开发者_开发技巧rect or not.


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;
    }
}


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜