输入字节数组在 40 处有不正确的结束字节

Input byte array has incorrect ending byte at 40

我有一个 base64 编码的字符串。它看起来像这样:

eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=

任何在线工具都可以将其解码为正确的字符串 {"bla1":"bla1","bla2":"bla2"}。但是,我的 Java 实施失败了:

import java.util.Base64;
System.out.println("payload = " + payload);
String json = new String(Base64.getDecoder().decode(payload));

我收到以下错误:

payload = eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 40

我的代码有什么问题?

好的,我知道了。 Base64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT); 使用 android.util.Base64 在 Android 设备上编码原始字符串。它使用 android.util.Base64.DEFAULT 编码方案。

然后在服务器端使用 java.util.Base64 时必须使用 Base64.getMimeDecoder().decode(payload) 而不是 Base64.getDecoder().decode(payload)

进行解码

我试图使用 args 中的字符串。我发现如果我使用 arg[0].trim() 就可以了。例如

Base64.getDecoder().decode(arg[0].trim());

我想可能是某种空白导致它搞砸了。

也许为时已晚,但我也遇到了这个问题。

默认情况下,Android Base64 实用程序会在编码字符串的末尾添加换行符。
Base64.NO_WRAP 标志告诉实用程序创建没有换行符的编码字符串。

您的 android 应用应编码 src 如下所示:

String encode = Base64.encodeToString(src.getBytes(), Base64.NO_WRAP);