Java 输入字节数组在 40 处的结束字节不正确
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35292836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input byte array has incorrect ending byte at 40
提问by toom
I have a string that is base64 encoded. It looks like this:
我有一个 base64 编码的字符串。它看起来像这样:
eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
Any online tool can decode this to the proper string which is {"bla1":"bla1","bla2":"bla2"}
. However, my Java implementation fails:
任何在线工具都可以将其解码为正确的字符串,即{"bla1":"bla1","bla2":"bla2"}
. 但是,我的 Java 实现失败了:
import java.util.Base64;
System.out.println("payload = " + payload);
String json = new String(Base64.getDecoder().decode(payload));
I'm getting the following error:
我收到以下错误:
payload = eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 40
What is wrong with my code?
我的代码有什么问题?
采纳答案by toom
Okay, I found out. The original String is encoded on an Android device using android.util.Base64
by Base64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT);
. It uses android.util.Base64.DEFAULT
encoding scheme.
好吧,我发现了。原始字符串在 Android 设备上使用android.util.Base64
by 进行编码Base64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT);
。它使用android.util.Base64.DEFAULT
编码方案。
Then on the server side when using java.util.Base64
this has to be decoded with Base64.getMimeDecoder().decode(payload)
notwith Base64.getDecoder().decode(payload)
然后在服务器端使用时java.util.Base64
,必须使用Base64.getMimeDecoder().decode(payload)
notwith进行解码Base64.getDecoder().decode(payload)
回答by JustGage
I was trying to use the strings from the args. I found that if I use arg[0].trim()
that it made it work. eg
我试图使用 args 中的字符串。我发现如果我使用arg[0].trim()
它就可以了。例如
Base64.getDecoder().decode(arg[0].trim());
I guess there's some sort of whitespace that gets it messed up.
我想有某种空白让它变得一团糟。
回答by Artem Komarov
Maybe too late, but I also had this problem.
也许为时已晚,但我也遇到了这个问题。
By default, the Android Base64 util adds a newline character to the end of the encoded string.
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character.
默认情况下,Android Base64 实用程序会在编码字符串的末尾添加一个换行符。
Base64.NO_WRAP 标志告诉实用程序创建没有换行符的编码字符串。
Your android app should encode src
something like this:
您的 android 应用程序应该编码src
如下:
String encode = Base64.encodeToString(src.getBytes(), Base64.NO_WRAP);