URL编码与中文的转换

 

public static String Encode(String str, String charset) { //将中文转换成URL编码
    Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
    Matcher m = p.matcher(str);
    StringBuffer b = new StringBuffer();
    while(m.find()){
      try {
        m.appendReplacement(b, URLEncoder.encode(m.group(), charset));
      }
      catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
      }
    }
    m.appendTail(b);
    return b.toString();
  }

  public static String Decode(String str) { //将URL编码转换成中文
    try {
      str = URLDecoder.decode(str, "UTF-8");
    }
    catch (Exception ex) {
      System.err.println("URLDecoder Error : " + str);
    }
    return str;
  }

你可能感兴趣的:(url)