java中判断一个字符串是绝对URL还是相对URL
给定一个字符串,在Java中如何判断它是绝对URL还是相对URL?我尝试了以下代码:
private boolean isAbsoluteURL(String urlString) {
boolean result = false;
try
{
URL url = new URL(urlString);
String protocol = url.getProtocol();
if (protocol != null && protocol.trim().length() > 0)
result = true;
}
catch (MalformedURLException e)
{
return false;
}
return result;
}
问题是所有相对网址(www.google.com
或 /questions/ask
)。由于没有定义协议,因此抛出 MalformedURLException
。
Given a string, how do I determine if it is an absolute URL or a relative URL in Java? I tried the following code:
private boolean isAbsoluteURL(String urlString) {
boolean result = false;
try
{
URL url = new URL(urlString);
String protocol = url.getProtocol();
if (protocol != null && protocol.trim().length() > 0)
result = true;
}
catch (MalformedURLException e)
{
return false;
}
return result;
}
The problem is that all relative URLs (www.google.com
or /questions/ask
). are throwing a MalformedURLException
because there is no protocol defined.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
更多信息此处。
How about this:
More info here.
正如我在 我的评论,您必须在检查之前对 URL 进行规范化,并且规范化取决于您的应用程序,因为
www.google.com
不是绝对 URL。下面是一个示例代码,可用于检查 URL 是否绝对:输出:
As I said in in my comment, you have to normalize the URL before checking it, and that normalization depends on your application, since
www.google.com
is not an absolute URL. Here is an example code, which can be used to check URLs to be absolute:Output:
这是我用来确保链接绝对的片段:
This is a snippet I use to ensure links are absolute:
我做了这个:
I made this: