HarmonyOS鸿蒙Next中字符串转为Base64

HarmonyOS鸿蒙Next中字符串转为Base64 加密过程中,使用base64将字符串转为Base64的时候,出现部分字符与java生成的字符不一致的问题

3 回复

造成的原因是android对特殊字符也做url编码,鸿蒙这边没有处理。参考下面,自己编码一遍

let textEncoder = new util.TextEncoder();
let name = "测试账号01:1234qwer,"
let result = textEncoder.encodeInto(name);
let base64Helper = new util.Base64Helper();
let base64Str = base64Helper.encodeToStringSync(result);
console.log('base64Str----', encodeURIComponent(base64Str))

更多关于HarmonyOS鸿蒙Next中字符串转为Base64的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)Next中,字符串转为Base64可以使用util模块提供的Base64工具类。具体步骤如下:

  1. 导入模块:首先需要导入util模块中的Base64类。

    import util from '[@ohos](/user/ohos).util';
    
  2. 创建Base64实例:使用Base64类的静态方法create()创建一个Base64实例。

    let base64 = new util.Base64();
    
  3. 编码字符串:调用encodeToString方法将字符串转为Base64编码。

    let str = "Hello, HarmonyOS!";
    let base64Str = base64.encodeToString(new util.TextEncoder().encode(str));
    console.log(base64Str);
    
  4. 解码Base64:如果需要将Base64字符串解码回原始字符串,可以使用decode方法。

    let decodedStr = new util.TextDecoder().decode(base64.decode(base64Str));
    console.log(decodedStr);
    

在HarmonyOS鸿蒙Next中,可以使用TextEncoderBase64类将字符串转换为Base64编码。以下是示例代码:

import { TextEncoder } from '@ohos.util';
import { Base64 } from '@ohos.util';

// 创建TextEncoder实例
const encoder = new TextEncoder();

// 将字符串编码为Uint8Array
const uint8Array = encoder.encode('Hello, HarmonyOS!');

// 使用Base64编码
const base64String = Base64.encodeToString(uint8Array, false);

console.log(base64String); // 输出Base64编码后的字符串

这段代码首先将字符串编码为Uint8Array,然后使用Base64.encodeToString方法将其转换为Base64字符串。

回到顶部