判断String是否包含中文
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
return m.find();
}
public static String chineseToURLEncodeUTF8(String chinese){
try {
String ret = "";
for(int i=0; i<chinese.length(); i++){
String tmpChar = String.valueOf(chinese.charAt(i));
if(isContainChinese(tmpChar)){
ret += URLEncoder.encode(tmpChar, "UTF-8");
}else{
ret += tmpChar;
}
}
return ret;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
注意:要对String中的每个字符单独判断是否属于中文。如果对整个String进行编码,则可能有误,例如"http://abc.def_你好"会把"://"也转换了