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