java 检查 URL 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5802980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check format of URL
提问by Ram
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.
我需要一个 Java 代码,它接受类似 URLhttp://www.example.com
并显示 URL 的格式是否正确。
回答by adarshr
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;
}
}
回答by Ruben Estrada
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).
根据@adarshr 的回答,我会说最好使用 URL 类而不是 URI 类,原因是 URL 类会将类似的内容标记htt://example.com
为无效,而 URI 类不会(我认为是问题的目标)。
//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;
}
}