您的位置:首页 > 移动开发 > Android开发

Android向远程发服务请求中文乱码解决方法--全部代码经验证-方法一

2016-02-19 16:27 411 查看
最近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;



}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: