Base64 and URL encoding and decoding operations

  • When downloading a file, sometimes the file name contains a Chinese name, and it will be garbled after downloading, so some encoding and decoding operations are performed on the file name to solve the garbled.
  • BASE64编解码(解决火狐浏览器乱码)
    1. new BASE64Encoder().encode (byte array to be encoded) —> encoding
    2. new BASE64Decoder().decodeBuffer (decoded content) —> Decode
  • URL编解码
    1. URLEncoder.encode (the content that needs to be encoded, "UTF-8"); —> encoding
    2. URLDecoder.decode (the content to be decoded, "UTF-8"); —> Decode

The sample code is as follows:

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);
}


}

Guess you like

Origin blog.csdn.net/qq_45796486/article/details/114818808