package com.test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64AndURLDecoder {
final static BASE64Encoder encoder = new BASE64Encoder();
final static BASE64Decoder decoder = new BASE64Decoder();
public static String encode(String str) throws UnsupportedEncodingException{
str=URLEncoder.encode(str,"UTF-8");
byte[] textByte = str.getBytes("UTF-8");
// 编码
String encodedText = encoder.encode(textByte);
return encodedText;
}
public static String decode(String str) throws IOException{
byte[] textByte = decoder.decodeBuffer(str);
String dString=new String(textByte,"UTF-8");
return URLDecoder.decode(dString,"UTF-8");
}
public static void main(String[] args) throws Exception {
String string="<p>测试</p>" ;
String string2=encode(string);
System.out.println(string2);
System.out.println(decode(string2));
}
}

本文介绍了如何在Java中使用Base64进行字符串编码和解码,通过实例展示了如何编码一个包含HTML标签的字符串,并能正确地进行解码还原。
1811

被折叠的 条评论
为什么被折叠?



