import Java.io.bytearray output stream;
import sun.misc.BASE64Decoder;
公共类URL utils {
//*
* URL加密这是转码的中文
*
编码格式: utf-8
*/
publicfinalstaticstringurlencode
try {
returnnotempty(s? Java.net.urlencoder.encode(s,' utf-8 ' ) : null;
}catch(exceptione ) {
返回空值;
}
}
//*
* URL解读这是解读
*/
publicstaticstringurldecode{
try {
returnnotempty(s? Java.net.URLdecoder.decode(s,' utf-8 ' ) : null;
}catch(exceptione ) {
返回空值;
}
}
//*
*检查是否为空
*
* @param s需要检查的字符串
* @return检查结果
*/
publicstaticbooleannotempty{
return s==null||s.trim ().length ) ) 1? 假:真;
}
对//S进行BASE64编码
publicstaticstringgetbase 64 (strings ) {
if (s==空) )。
返回空值;
return (news un.misc.base64 encoder () ).encode (s.getbytes ) );
}
对用BASE64编码的字符串s进行解码
公共字符串框架64 (字符串)。
if (s==空) )。
返回空值;
base64解码器=new base64解码器(;
try {
byte[]b=decoder.decodebuffer(s );
返回新字符串(b );
}catch(exceptione ) {
返回空值;
}
}
/*
*十六进制数字字符集
*/
privatestaticstringhexstring=' 0123456789 abcdef ';
/*
*将字符串编码为十六进制,并应用于所有字符,包括中文
*/
publicstaticstringencode{
//从默认编码获取字节数组
byte[] bytes=str.getBytes (;
stringbuilder sb=new stringbuilder (bytes.length *2);
//将字节数组中的每个字节分解为2位十六进制整数
for(intI=0; i bytes.length; I ) {
sb.append(HEXstring.Charat ) (bytes[I]0xf0)4);
sb.append(HEXstring.Charat ) (bytes[I]0x0f )0) );
}
return sb.toString (;
}
/*
*将十六进制解码为字符串,并应用于包括中文在内的所有字符
*/
publicstaticstringdecode (string bytes ) {
bytearrayoutputstreambaos=newbytearrayoutputstream (
bytes.length ()/2 );
//将每个2位的十六进制整数组装成1字节
for(intI=0; i bytes.length (; i =2)
BAOS.write((hexstring.indexof ) bytes.charat ) I )4 | hexString
. indexof(bytes.Charat ) I1 ) );
返回新字符串(baos.to bytearray ) );
}
publicstaticvoidmain (string [ ] args ) throws Exception { )。
strings test=' http://localhost :8026/loginservlet.do? username='漂亮的钢笔userpass='123 ' ';
system.out.println(urlencode ) stest );
system.out.println(urldecode ) stest );
system.out.println (URL utils.encode ('中') );
system.out.println (URL utils.decode (' d6d0) );
}
}