1 package com.utils.test;
2
3 import org.apache.commons.codec.binary.Base64;
4 import org.junit.Test;
5
6 public class Base64Test {
7
8 /**
9 * 使用sun.misc.BASE64Encoder 和 sun.misc.BASE64Decoder
10 * 进行编码解码
11 * @throws Exception
12 */
13 @Test
14 public void base64Test1() throws Exception{
15 String str = "hello";
16 byte[] bytes = str.getBytes("utf-8");
17 // Base64编码
18 str = new sun.misc.BASE64Encoder().encode(bytes);
19 System.out.println("Base64编码: " + str);
20 // Base64解码
21 bytes = new sun.misc.BASE64Decoder().decodeBuffer(str);
22 str = new String(bytes, "utf-8");
23 System.out.println("Base64解码: " + str);
24 }
25 /**
26 * 需要 commons-codec-1.10.jar
27 * 使用org.apache.commons.codec.binary.Base64
28 * 进行编码解码
29 * @throws Exception
30 */
31 @Test
32 public void base64Test2() throws Exception{
33 String str = "hello";
34 byte[] bytes = str.getBytes("utf-8");
35 //编码
36 bytes = Base64.encodeBase64(bytes);
37 str = new String(bytes,"utf-8");
38 System.out.println(str);
39 // 解码
40 bytes = Base64.decodeBase64(str);
41 str = new String(bytes, "utf-8");
42 System.out.println(str);
43 }
44
45 }