我想将URL拆分为不同的组件,类似于JavaScript中的location对象。我想要的部分是:哈希,主机,主机名,路径名,端口,协议和查询字符串。我想要拆分的网址是:http://localhost:8080/settings/settings.php?setting=layout&value=normal#appearance
。
目前,我有:
Dim url as String = "http://localhost:8080/settings/settings.php?setting=layout&value=normal#appearance"
Dim protocol as String = url.Split("://")(0)
Dim hash = url.Split("#")(1)
Dim query as String = url.Split("?")(1).Split("#")(0)
但我认为它不高效或可靠。我也不知道如何获得剩下的部分。
是否有更有效的方法来获取查询字符串?如何将URL拆分为我描述的部分?
答案 0 :(得分:5)
使用内置类System.Uri
,它可以自动为您完成所有解析:
Dim url as String = "http://localhost:8080/settings/settings.php?setting=layout&value=normal#appearance"
Dim uri as New Uri(url)
使用Uri
的实例,您应该能够轻松检索所有这些部分。
Dim protocol as String = uri.Scheme ' http
Dim host as String = uri.Host ' localhost
Dim port as Integer = uri.Port ' 8080
Dim path as String = uri.AbsolutePath ' /settings/settings.php
Dim querystring as String = uri.Query ' ?setting=layout&value=normal
Dim hash as String = uri.Fragment ' #appearance