为什么我对相同文本的 python 和 java base64 编码有不同的结果?

Why I have different results for python and java base64 encode for the same text?

我在 python 和 java 中有两个代码如下,但是 运行 它们的结果不同,发生了什么事?

python2.7代码:

#encoding:utf-8
import json
import base64

st_test = {"test":"测试内容"}
body = json.dumps(st_test,ensure_ascii=False)
res = base64.b64encode(body)
prin res 
#eyJ0ZXN0IjogIua1i+ivleWGheWuuSJ9

Java代码:

import java.util.Base64;

body = "{\"test\":\"测试内容\"}";
String body64 = Base64.getEncoder().encodeToString(body.getBytes("UTF-8")) ;
System.out.println(body64);
//eyJ0ZXN0Ijoi5rWL6K+V5YaF5a65In0=

您有两个不同的字符串 - Java:

之后没有 space

如果我删除 space

body = body.replace(' ', '')

然后我得到相同的代码


import json
import base64

st_test = {"test": "测试内容"}
body = json.dumps(st_test, ensure_ascii=False)
print body

body = body.replace(' ', '')
print body

res = base64.b64encode(body)
print res
print (res == 'eyJ0ZXN0Ijoi5rWL6K+V5YaF5a65In0=')

结果

{"test": "测试内容"}
{"test":"测试内容"}
eyJ0ZXN0Ijoi5rWL6K+V5YaF5a65In0=
True