Java中对进行Base64编码的有如下三种方式:
方式一:commons-codec.jar 【推荐】
官网:http://commons.apache.org/proper/commons-codec/archives/1.11/userguide.html
maven项目需要的依赖:
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency>
String base64String="whuang123"; byte[] result = Base64.encodeBase64(base64String.getBytes());
方式二:使用sun.misc.BASE64Encoder
/** * 编码 * * @param content * @return */ public static String encode(byte[] content) { return new sun.misc.BASE64Encoder().encode(content); } /** * 解码 * * @param source * @return */ public static byte[] decode(String source) { try { sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder(); return decoder.decodeBuffer(source); } catch (IOException e) { e.printStackTrace(); } return null; }
方式三:使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64
/** * 编码 * * @param input * @return * @throws Exception */ public static String encodeBase64(byte[] input) throws Exception { Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); Method mainMethod = clazz.getMethod("encode", byte[].class); mainMethod.setAccessible(true); Object retObj = mainMethod.invoke(null, new Object[]{input}); return (String) retObj; } /** * 解码 * * @param input * @return * @throws Exception */ public static byte[] decodeBase64(String input) throws Exception { Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); Method mainMethod = clazz.getMethod("decode", String.class); mainMethod.setAccessible(true); Object retObj = mainMethod.invoke(null, input); return (byte[]) retObj; }