Dart:从 URL 获取主机、路径和查询参数
在 Dart 中,您可以按照以下步骤从给定的 URL 字符串中提取有用的信息:
- 从你的 URL 字符串构造一个 Uri 对象:
const url = "...";
const uri = Uri.parse(url);
2、现在,你可以通过Uri对象的各种属性得到你想要的。以下是最常用的:
- origin:基本 URL(如下所示:protocol://host:port)
- host:URL 的主机部分(域、IP 地址等)
- 方案:协议(http、https等)
- 端口:端口号
- 路径:路径
- pathSegments : URI 路径拆分为其段
- query : 查询字符串
- queryParameters : 查询被拆分成一个地图,方便访问
您可以在官方文档中找到有关Uri 类的更多详细信息。
例子:
// main.dart
void main() {
// an ordinary URL
const urlOne = 'https://www.kindacode.com/some-category/some-path/';
final uriOne = Uri.parse(urlOne);
print(uriOne.origin); // https://www.kindacode.com
print(uriOne.host); // www.kindacode.com
print(uriOne.scheme); // https
print(uriOne.port); // 443
print(uriOne.path); // /some-category/some-path/
print(uriOne.pathSegments); // [some-category, some-path]
print(uriOne.query); // null
print(uriOne.queryParameters); // {}
// a URL with query paramters
const urlTwo =
'https://test.kindacode.com/one-two-three?search=flutter&sort=asc';
final uriTwo = Uri.parse(urlTwo);
print(uriTwo.origin); // https://test.kindacode.com
print(uriTwo.host); // test.kindacode.com
print(uriTwo.scheme);
print(uriTwo.port); // 443
print(uriTwo.path); // /one-two-three
print(uriTwo.pathSegments); // [one-two-three]
print(uriTwo.query); // search=flutter&sort=asc
print(uriTwo.queryParameters); // {search: flutter, sort: asc}
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。