Java对URL中的中文进行UrlEncode

有些中文或者有空格的、传入参数带中文的URL需要用如下方式进行encode方能进行真正的请求:

public static String urlEncodeURL(String str) {
        try {
            String result = URLEncoder.encode(str, "UTF-8");
            result = result.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");//+实际上是 空格 url encode而来
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

只对url地址中的中文进行编码

public static String encode(String url)    {        
try {             
  Matcher matcher =Pattern.compile([\\u4e00\\u9fa5]").matcher(url);             
  int count = 0;             
  while (matcher.find()) {               
  //System.out.println(matcher.group());   String tmp=matcher.group();
  url=url.replaceAll(tmp,java.net.URLEncoder.encode(tmp,"gbk"));
  }   // System.out.println(count);   //url = java.net.URLEncoder.encode(url,"gbk"); } catch (UnsupportedEncodingException e) {   // TODO Auto-generated catch block
  e.printStackTrace(); } return url; }

 

上一篇:数字转汉字


下一篇:String------replaceFirst、replaceAll、replace区别