如何检查 URL 中是否存在协议(protocol),如果不存在则需要附加它。 是否有任何类可以在 Java 中实现这一点? 例如:字符串 URL = www.google.com
最佳答案
只需使用 String.startsWith("http://")
来检查。
public String ensure_has_protocol(final String a_url)
{
if (!a_url.startsWith("http://"))
{
return "http://" + a_url;
}
return a_url;
}
编辑:
另一种方法是使用 java.net.URL
实例,如果 URL 不包含(合法的)协议(protocol),其构造函数将抛出 java.net.MalformedURLException
(或因任何其他原因无效):
public URL make_url(final String a_url) throws MalformedURLException
{
try
{
return new URL(a_url);
}
catch (final MalformedURLException e)
{
}
return new URL("http://" + a_url);
}
您可以使用 URL.toString()
获取 URL 的字符串表示形式。这是对 startsWith()
方法的改进,因为它保证返回 URL 有效。
关于java - 如何检查 url 中是否存在协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9363134/