HarmonyOS URI字符串解析 常用的几个方法

52 阅读2分钟

HarmonyOS 使用 URI字符串解析 的好处

  1. 标准化解析

    • HarmonyOS的URI字符串解析方法遵循RFC 3986等标准,确保了对URI的标准化解析,提高了解析的准确性和一致性。
  2. 易用性

    • 提供了简洁明了的API接口,使得开发者可以轻松地构造、解析和比较URI对象,降低了开发难度和复杂度。
  3. 灵活性

    • 支持对URI的各个组成部分进行单独访问和修改,满足了不同应用场景下的需求。例如,可以只获取URI的主机名部分,或者修改URI的查询参数等。
  4. 安全性

    • 在解析URI时,能够正确处理特殊字符和编码问题,避免了因解析错误而导致的安全漏洞。

本模块专注于提供URI字符串解析的功能,严格遵循RFC3986规范标准,该标准详细定义了网络资源的标识符的编码与解析方法。请注意,本模块仅支持标准场景下的URI解析,对于非标准或特殊场景下的解析需求,可能无法直接支持。

URI字符串解析

1. constructor

2. toString

3. equalsTo

4. checkIsAbsolute

1. constructor

constructor(uri: string)

constructor是URI的构造函数。

参数:

参数名类型必填说明
uristring入参对象。

使用方式:

let mm = 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment';
new uri.URI(mm);

new uri.URI('https://username:password@host:8080');

2. toString

toString(): string

将URI转化为编码后的字符串。

返回值:

类型说明
string返回URI的字符串序列化。

 使用方式:

const result = new uri.URI('https://username:password@host:8080/directory/file?ab=pppppp#qwer da');
let result1 = result.toString(); 

输出:

输出结果: https://username:password@host:8080/directory/file?ab=pppppp#qwer%20da

3. equalsTo

equalsTo(other: URI): boolean

判断此URI是否与其他URI对象相等。

参数:

参数名类型必填说明
otherURI需要比较的URI对象。

返回值:

类型说明
boolean返回true表示相等,否则返回false。

使用方式:

const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da');
const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da');
let result = uriInstance.equalsTo(uriInstance1); 

输出:

输出结果:true

4. checkIsAbsolute

checkIsAbsolute(): boolean

判断此URI是否为绝对URI(是否定义了scheme组件)。

返回值:

类型说明
boolean如果是绝对URI返回true,否则返回false。

使用方式一:

const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp');
console.info(`${uriInstance.checkIsAbsolute()}`); 

输出:

输出结果:true

使用方式二:

const uriInstance1 = new uri.URI('xxx.com/suppliers.htm');
console.info(`${uriInstance1.checkIsAbsolute()}`); 

输出:

输出结果:false

 如需要其他方法 请参考官方文档

制作不易 点个关注再走吧。°(°¯᷄◠¯᷅°)°。