我想将一个字符串编码为 base64
并通过套接字传输并解码回来。
但解码后给出不同的答案。
以下是我的代码,结果是“77+9x6s="
import javax.xml.bind.DatatypeConverter;
public class f{
public static void main(String a[]){
String str = new String(DatatypeConverter.parseBase64Binary("user:123"));
String res = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println(res);
}
}
你知道如何实现吗?
最佳答案
您可以使用以下方法:
import org.apache.commons.codec.binary.Base64;
// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));
// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));
希望这能解答您的疑问。
关于java - Base64 Java 编码和解码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743851/