您需要更改类的导入:
import org.apache.commons.codec.binary.Base64;
然后将您的类更改为使用Base64类.
以下是一些示例代码:
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
那就读why you shouldn't use sun.* packages.
更新(2016-12-16)
You can now use java.util.Base64
with Java 8. First, import it as you normally do:
import java.util.Base64;
然后使用Base64静态方法,如下所示:
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
如果您想直接对字符串进行编码,并以编码字符串的形式得到结果,可以使用如下方式:
String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
有关更多信息,请参见Java documentation for Base64.