最近Android编写电子商城,研发解析类似的商城源码基础上独自完成类似京东商城的电子商务系统开发。
其中Android系统远程调用后台服务经常发生中文乱码问题,求之网上诸多方法,包括前端设置编码格式URLEncoder.encode(request, "UTF-8"),后端request.setCharacterEncoding("UTF-8");解密等诸多方法都未能凑效。
最后通过摸索尝试两种方法可行:
方法一:
前台 :对中文参数线做字符转码
string str_payway = ShopUtils.changeToUnicode(“中国程序员万岁“);
定义 ShopUtils.changeToUnicode方法为:
public class ShopUtils {
/**
* 转换编码
*/
public static String changeToUnicode(String str) {
StringBuffer strBuff = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
String temp = Integer.toHexString(str.charAt(i));
if (temp.length() != 4) {
temp = "00" + temp;
}
if (temp.equals("00d")) {
temp = "0" + temp;
}
if (temp.equals("00a")) {
temp = "0" + temp;
}
strBuff.append(temp.substring(0, temp.length() - 2));
strBuff.append(temp.substring(temp.length() - 2, temp.length()));
}
String returnData = strBuff.toString();
return returnData;
}
}
后台: 对字符进行反向转换,还原成汉字
UncodeUtil.changeToWord(request.getParameter("address"));
public class UncodeUtil {
public static String changeToWord(String str) {
String retData = null;
String tempStr = new String(str);
String[] chStr = new String[str.length()/4];
for(int i=0;i<str.length();i++){
if(i%4==3){
chStr[i/4] = new String(tempStr.substring(0, 4));
tempStr = tempStr.substring(4, tempStr.length());
}
}
char[] retChar = new char[chStr.length];
for(int i=0;i<chStr.length;i++){
retChar[i] = (char) Integer.parseInt(chStr[i], 16);
}
retData = String.valueOf(retChar, 0, retChar.length);
return retData;
}
}