如何检查 url 中是否存在协议?
如何检查 URL 中是否存在协议,如果不存在则需要附加它。 java中有没有类可以实现这个功能? 例如:String URL = www.google.com
how to check protocol is present in URL , if not present need to append it.
is there any class to achieve this in java?
eg: String URL = www.google.com
need to get http://www.google.com
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
String.startsWith("http://")
来检查这一点。编辑:
另一种方法是使用 java.net.URL 实例,如果 URL 不包含(合法)协议,其构造函数将抛出 java.net.MalformedURLException (或因任何其他原因无效):
您可以使用
URL.toString()
获取 URL 的字符串表示形式。这是对startsWith()
方法的改进,因为它保证返回 URL 有效。Just use
String.startsWith("http://")
to check this.EDIT:
An alternative would use a
java.net.URL
instance, whose constructor would throw anjava.net.MalformedURLException
if the URL did not contain a (legal) protocol (or was invalid for any other reason):You can use
URL.toString()
to obtain string representation of the URL. This is an improvement on thestartsWith()
approach as it guarantees that return URL is valid.假设您有
String url = www.google.com
。字符串类方法足以实现检查协议标识符的目标。例如,url.startsWith("https://")
将检查特定字符串是否以给定协议名称开头。然而,这些控制足以进行验证吗?
我认为它们还不够。首先,您应该定义一个有效协议标识符的列表,例如像
{"http", "ftp", "https", ...
} 这样的字符串数组。然后,您可以使用正则表达式("://")
解析您的输入字符串,并测试您的 URL 标头是否属于有效协议标识符列表。域名验证方法超出了这个问题,您也可以/应该使用不同的技术来处理它。Let's say you have
String url = www.google.com
. String class methods would be enough for the goal of checking protocol identifiers. For example,url.startsWith("https://")
would check whether a specific string is starting with the given protocol name.However, are these controls enough for validation?
I think they aren't enough. First of all, you should define a list of valid protocol identifiers, e.g. a String array like
{"http", "ftp", "https", ...
}. Then you can parse your input String with regex("://")
and test your URL header whether it belongs to the list of valid protocol identifiers. And domain name validation methods are beyond this question, you can/should handle it with different techniques as well.为了完整起见,我会做类似以下的事情:
Just for completeness, I would do something like the following: