鸿蒙ArkTs url safe Base64的处理

271 阅读1分钟

接口返回Base64编码的数据,有时是经过url safe处理的,在Android上,有现成的处理方式:

Base64.decode(response.getData().getBytes(), Base64.URL_SAFE);

而在鸿蒙ArkTs下,目前未发现现成的方法,需要自己处理。 在处理前,需要理解url safe做了哪些处理:

  • 将+转为-
  • 将/转为_
  • 移除末尾的=

因此,反推过来,处理代码如下:

//转换规则:所有-转换为+,所有_转换为/,最后在末尾加=,直到字符串length能被4整除
static handleUrlSafeBase64(urlSafeBase64: string): string {
  let normalBase64 = urlSafeBase64.replace(/-/g, "+").replace(/_/g, "/") + "="
  while (normalBase64.length % 4 != 0) {
    normalBase64 = normalBase64 + "="
  }
  return normalBase64
}