下面是生成base64编码字符串的python代码:
base64str = base64.encodestring('%s:' % getpass.getuser())我希望使用Java实现相同的base64str。下面是我的Java代码片段:
String user = System.getProperty("user.name");
byte[] encoded_str = Base64.encodeBase64(user.getBytes());
String encoded_string = new String(encoded_str).trim();无论如何,python编码的字符串与Java不同。我使用的是“导入org.apache.commons.codec.binary.Base64;”库。
知道吗?
发布于 2014-07-21 19:00:40
在调用Base64之前,python代码将冒号附加到输入字符串中。
>>> print '%s:' % 'test'
test:当我将冒号添加到您的java代码中时,我能够在测试中获得相同的结果(python和Java),
String user = System.getProperty("user.name") + ":";
byte[] encoded_str = Base64.encodeBase64(user
.getBytes());
String encoded_string = new String(encoded_str)
.trim();
System.out.println(encoded_string);发布于 2014-07-21 19:03:40
Java中的String.getBytes()不能保证使用的字符集。使用String.getBytes(String)来始终确保您得到了所需的编码。
user.getBytes("UTF-8")https://stackoverflow.com/questions/24872557
复制相似问题