BASE64转码

前台的URL中最好不要出现中文,在跳转前可以进行转码,使用URLEncode或者encodeURIComponent转码

 

URLEncode这种方式有两种:

第一种:

传参前:使用java.net.URLEncoder.encode("xxxx",utf-8")将中文转为16进制字符。

接收参数后:使用java.net.URLDncoder.decode("xxxx",utf-8")16进制字符转为中文。

这种方式需要注意的是,在使用encode转码后,会出现特殊字符,这时候,就需要将特殊字符替换为相应的16进制。因为特殊字符在url路径中做为参数传递时,也是乱码。

 

第二种:

传参前:encodeURI(xxxx)  

接收参数后:使用java.net.URLDncoder.decode("xxxx",utf-8")16进制字符转为中文。

这种方式需要注意的是,在使用encodeURI转码后,会出现特殊字符,这时候,就需要将特殊字符也转码,所以使用两次encodeURI即:

encodeURIencodeURI(“xxxx”))。

 

这两种转码方式是很好用的,所以很建议大家使用。

 

 

 1 // 将 s 进行 BASE64 编码    
 2 public static String getBASE64(String s) {    
 3 if (s == null) return null;    
 4 return (new sun.misc.BASE64Encoder()).encode( s.getBytes() );    
 5 }    
 6  
 7 // 将 BASE64 编码的字符串 s 进行解码    
 8 public static String getFromBASE64(String s) {    
 9 if (s == null) 
10 return null;    
11 BASE64Decoder decoder = new BASE64Decoder();    
12 try {    
13 byte[] b = decoder.decodeBuffer(s);    
14 return new String(b);    
15 } catch (Exception e) {    
16 return null;    
17 }    
18 }   
19     public static void main(String[] args) {
20 //        String string = new String(Base64.decodeBase64("eyJjX2lkIjoxLCJjX25hbWUiOiLmsYnor60ifQ".getBytes()));
21 //        System.out.println(string);
22     String string = getBASE64("cell制程");
23     System.out.println(string);
24     string = getFromBASE64(string);
25     System.out.println(string);
26 //        System.out.println(new String(Base64.decodeBase64("eyJjX2lkIjoxLCJjX25hbWUiOiLmsYnor60ifQ".getBytes())));
27 }

 

posted @ 2014-03-24 14:44  暖暖的拥抱  阅读(946)  评论(0编辑  收藏  举报