import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* 对URL进行加密类
*
* @author <a href="mailto:jiangtao@ultrapower.com.cn">jiangtao</a>
*
* @version $Revision$
*/
public class URLEncoder {
private static char[] tab = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* 加密方式
* @param s 要加密的串
* @return 加密后的串
*/
public static String encode(String s) {
try {
if (s == null || s.equals("")) return "";
StringBuilder tmpStr = new StringBuilder();
byte tmpByte[] = s.getBytes();
for (byte aTmpByte : tmpByte)
tmpStr.append("").append(tab[0x0f & (aTmpByte >> 4)]).append(tab[0x0F & aTmpByte]);
return tmpStr.toString();
} catch (Exception e) {
e.printStackTrace();
return s;
}
}
/**
* 解密方法
* @param s 要加密的串
* @return 解密后的串
*/
public static String decode(String s) {
try {
if (s == null || s.equals("")) return "";
ByteArrayOutputStream bytess = new ByteArrayOutputStream();
byte tmpByte[] = s.toUpperCase().getBytes();
for (int i = 0; i < tmpByte.length / 2; i++) {
tmpByte[i * 2] = pocb(tmpByte[i * 2]);
tmpByte[i * 2 + 1] = pocb(tmpByte[i * 2 + 1]);
bytess.write((tmpByte[i * 2] << 4) | (tmpByte[i * 2 + 1]));
}
bytess.flush();
return new String(bytess.toByteArray());
} catch (Exception e) {
return s;
}
}
private static byte pocb(byte b) {
if (b > 57) {
b -= 55;
} else {
b -= 48;
}
return b;
}
public static String encodeBase64(String str) {
byte[] b = str.getBytes();
return new sun.misc.BASE64Encoder().encode(b);
}
public static String decodeBase64(String fileContent) throws IOException {
byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(fileContent);
return new String(b);
}
/**
* @param args
*/
public static void main(String[] args) {
String url = "url=XX中文//、中文测试ttt../test/bop.jsp?menuid=2020100007&menu=中国&";
System.out.println("encode :" + URLEncoder.encode(url));
System.out.println("decode :" + URLEncoder.decode("687474703A2F2F7777772E626F6D632E636F6D3A383038312F7569702F6F7065726174696F6E2F626F70506F7065646F6D21626F70547265652E706F7274616C"));
}
}