flutter如何实现URL编码

在Flutter中如何对URL进行编码?我在处理包含特殊字符的URL时遇到了问题,比如空格和中文应该如何正确编码?是否有内置的方法或者需要引入第三方库?具体该如何实现?求各位大神指点。

2 回复

Flutter中可通过Uri.encodeComponent()Uri.encodeFull()进行URL编码。前者编码特殊字符,后者保留完整URL结构。示例:

String encoded = Uri.encodeComponent('hello world');
// 输出:hello%20world

更多关于flutter如何实现URL编码的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现URL编码有以下几种方式:

1. 使用 dart:core 的 Uri 类

import 'dart:core';

void main() {
  String originalUrl = "https://example.com/测试路径?name=张三&age=20";
  
  // 对整个URL进行编码
  String encodedUrl = Uri.encodeFull(originalUrl);
  print(encodedUrl);
  // 输出: https://example.com/%E6%B5%8B%E8%AF%95%E8%B7%AF%E5%BE%84?name=%E5%BC%A0%E4%B8%89&age=20
  
  // 对查询参数进行编码
  String query = "name=张三&age=20";
  String encodedQuery = Uri.encodeComponent(query);
  print(encodedQuery);
  // 输出: name%3D%E5%BC%A0%E4%B8%89%26age%3D20
}

2. 使用 Uri 类的组件编码

void encodeUrlComponents() {
  String path = "测试路径";
  String queryParam = "张三";
  
  String encodedPath = Uri.encodeComponent(path);
  String encodedParam = Uri.encodeComponent(queryParam);
  
  String url = "https://example.com/$encodedPath?name=$encodedParam";
  print(url);
}

3. 解码URL

void decodeUrl() {
  String encodedUrl = "https://example.com/%E6%B5%8B%E8%AF%95%E8%B7%AF%E5%BE%84";
  
  String decodedUrl = Uri.decodeFull(encodedUrl);
  print(decodedUrl);
  // 输出: https://example.com/测试路径
  
  String encodedComponent = "%E5%BC%A0%E4%B8%89";
  String decodedComponent = Uri.decodeComponent(encodedComponent);
  print(decodedComponent);
  // 输出: 张三
}

主要方法说明:

  • Uri.encodeFull(): 编码完整URL,保留URL结构(不编码 : / ? & = 等符号)
  • Uri.encodeComponent(): 编码URL组件,会对所有特殊字符进行编码
  • Uri.decodeFull(): 解码完整URL
  • Uri.decodeComponent(): 解码URL组件

推荐使用 Uri.encodeComponent() 来处理URL参数,使用 Uri.encodeFull() 来处理完整URL。

回到顶部