当前位置:   article > 正文

Base64和URL编解码操作_base64encoder().encode

base64encoder().encode
  • 在下载文件的时候有时候文件名称中含有中文名,下载下来后会乱码,所以就对文件名称进行一些编解码操作,来解决乱码。
  • 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);
}


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/146859
推荐阅读
相关标签
  

闽ICP备14008679号