Base64和URL编解码操作

  • 在下载文件的时候有时候文件名称中含有中文名,下载下来后会乱码,所以就对文件名称进行一些编解码操作,来解决乱码。
  • BASE64编解码(解决火狐浏览器乱码)
    1. new BASE64Encoder().encode(需要编码的字节数组) —> 编码
    2. new BASE64Decoder().decodeBuffer(解码内容) —> 解码
  • URL编解码
    1. URLEncoder.encode(需要编码的内容, “UTF-8”); —> 编码
    2. URLDecoder.decode(需要解码的内容,“UTF-8”); —> 解码

示例代码如下:

public class EncoderTest {

public static void main(String[] args) throws Exception {
    Base64Test();
    URLEncoderTest();
}

private static String string = "这是需要编码的内容";

public static void Base64Test() throws Exception{

    // 创建Base64编码器
    BASE64Encoder base64Encoder = new BASE64Encoder();
    // 执行Base64编码操作
    String encode = base64Encoder.encode(string.getBytes("UTF-8"));
    System.out.println("Base64编码后的内容:"+encode);

    // 创建Base64解码器
    BASE64Decoder base64Decoder = new BASE64Decoder();
    // 执行Base64解码操作,因为编码的时候操作对象就是字节数组,所以解码的返回值也是一个字节数组
    byte[] bytes = base64Decoder.decodeBuffer(encode);
    // 使用指定的字符集解码指定的字节数组,构造一个新的String
    String string = new String(bytes, "UTF-8");

    System.out.println("Base64解码后的内容:"+string);
}

public static void URLEncoderTest() throws Exception {

    // url编码
    String encode = URLEncoder.encode(string, "UTF-8");
    System.out.println("URL编码后的内容为:"+encode);
    // url解码
    String decode = URLDecoder.decode(encode,"UTF-8");
    System.out.println("URL解码后的内容为:"+decode);
}


}

猜你喜欢

转载自blog.csdn.net/qq_45796486/article/details/114818808