[英]Encode/decode Base64 fails
in my application client-server, on client side I send the file content in following format: 在我的应用程序客户端服务器中,在客户端,我以以下格式发送文件内容:
public static String getImageFromURI (Context contesto, Uri uri) {
InputStream is;
ByteArrayOutputStream bos;
try {
is = contesto.getContentResolver().openInputStream(uri);
bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = is.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
}
} catch (IOException ex) {
Log.d("TAG_F2S", "Sono nel catch IOExcetion con emssage = " + ex.getMessage());
ex.printStackTrace();
return null;
}
return new String (Base64.encode(bos.toByteArray(), Base64.DEFAULT), "UTF-8");
} catch (FileNotFoundException fnfe) {
Log.d("TAG_F2S", "Sono nel catch FileNotFoundExcetion con emssage = " + fnfe.getMessage());
fnfe.printStackTrace();
return null;
} catch (UnsupportedEncodingException uee) {
Log.d("TAG_F2S", "Sono nel catch UnsupportedEncodingExcetion con emssage = " + uee.getMessage());
uee.printStackTrace();
return null;
}
}
and on server side I try to create the file as follow: 在服务器端,我尝试创建文件,如下所示:
byte [] byteFile = java.util.Base64.getDecoder ().decode(contenuto.getBytes("UTF-8"));
Files.write(Paths.get(myPath), byteFile);
But I can't obtain the result cause the exception like this: 但是我无法获得结果导致这样的异常:
java.lang.IllegalArgumentException: Illegal base64 character a
at java.util.Base64$Decoder.decode0(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
....
What's my error? 我怎么了 I don't understand.. Thanks for your help.
我不明白。谢谢您的帮助。
EDIT: The String that i send to the server is the following: https://codeshare.io/GqQWNA 编辑:我发送到服务器的字符串如下: https : //codeshare.io/GqQWNA
I found the problem: 我发现了问题:
when I encode the file content and I send data to the server in POST request, the content is modified replacing alland only '+' characters with ' ' (whitespace). 当我对文件内容进行编码并在POST请求中将数据发送到服务器时,将修改内容,并用''(空格)替换所有且仅将'+'字符替换。 Operating the following action on server side:
在服务器端执行以下操作:
java.util.Base64.getMimeDecoder().decode(contenuto.replace(" ", "+"));
I don't have the problem. 我没有问题。 Note that i used getMimeDecoder and not getDecoder , otherwise it doesn't work.
请注意,我使用的是getMimeDecoder而不是getDecoder ,否则它不起作用。
Does anyone know the reason for this problem? 有人知道这个问题的原因吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.