【问题标题】:Base64 UTF-32 decoding in java not working as expectedJava中的Base64 UTF-32解码无法按预期工作
【发布时间】:2020-07-25 23:36:22
【问题描述】:

我有 Base64 UTF-32 编码的字符串,在解码时带有空格。 我正在使用 org.apache.commons.codec 库。

使用下面的编码并按预期正常工作

public static String encodeBase64(String encodeString,String utfType){
        try {
            return new String(Base64.encodeBase64String(encodeString.getBytes(utfType)));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
        System.out.println(encodeBase64("This is UTF-32 encoading test","UTF-32"));

这给了我 Base64 编码的字符串

AAAAVAAAAGgAAABpAAAAcwAAACAAAABpAAAAcwAAACAAAABVAAAAVAAAAEYAAAAtAAAAMwAAADIAAAAgAAAAZQAAAG4AAABjAAAAbwAAAGEAAABkAAAAaQAAAG4AAABnAAAAIAAAAHQAAABlAAAAcwAAAHQ=

我想解码上面的字符串

    public static String decodeBase64(String decodeString,String utfType){
        try {
            byte[] actualByte = java.util.Base64.getDecoder() .decode(decodeString);
             return new String(actualByte);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

        System.out.println(decodeBase64("AAAAVAAAAGgAAABpAAAAcwAAACAAAABpAAAAcwAAACAAAABVAAAAVAAAAEYAAAAtAAAAMwAAADIAAAAgAAAAZQAAAG4AAABjAAAAbwAAAGEAAABkAAAAaQAAAG4AAABnAAAAIAAAAHQAAABlAAAAcwAAAHQ=","UTF-32"));

收到的输出如下,不正确

T   h   i   s       i   s       U   T   F   -   3   2        e   n   c   o   a 
  d   i   n   g        t   e   s   t

如何在解码后将其作为原始字符串获取如下值 这是UTF-32编码测试","UTF-32

【问题讨论】:

    标签: java base64 tobase64string


    【解决方案1】:

    您忘记将字符编码传递给 String 构造函数,因此它使用平台默认字符编码创建字符串。使用:

    return new String(actualByte, utfType);
    

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 1970-01-01
      • 2023-03-24
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 2018-04-20
      • 1970-01-01
      相关资源
      最近更新 更多