URLEncoder的只编码中文字符的类

来源:互联网 发布:建行网络学系统登录 编辑:程序博客网 时间:2024/05/16 08:07
原文地址:

  1. package log;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URLEncoder;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. /**
  7.  * 正则替换字符串里面的汉字部分。
  8.  * 
  9.  * @author 赵学庆 www.java2000.net
  10.  */
  11. public class URLEncoderHZ {
  12.   public static void main(String[] args) throws Exception {
  13.     String str = "http://192.168.1.1:8080/resources/电话.xls";
  14.     System.out.println(encode(str, "UTF-8"));
  15.   }
  16.   private static String zhPattern = "[/u4e00-/u9fa5]+";
  17.   /**
  18.    * 替换字符串卷
  19.    * 
  20.    * @param str 被替换的字符串
  21.    * @param charset 字符集
  22.    * @return 替换好的
  23.    * @throws UnsupportedEncodingException 不支持的字符集
  24.    */
  25.   public static String encode(String str, String charset) throws UnsupportedEncodingException {
  26.     Pattern p = Pattern.compile(zhPattern);
  27.     Matcher m = p.matcher(str);
  28.     StringBuffer b = new StringBuffer();
  29.     while (m.find()) {
  30.       m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
  31.     }
  32.     m.appendTail(b);
  33.     return b.toString();
  34.   }
  35. }

运行结果
http://192.168.1.1:8080/resources/%E7%94%B5%E8%AF%9D.xls