标签:
1 2 static final String regEx = "[\\u4e00-\\u9fa5]+"; 3 4 /**对数据内容为String的json字符串里的values里的汉字进行URLEncoding GBK的编码*/ 5 public static String encodingSocketData(String socketData){ 6 7 ///判断有没有中文 8 if ((!TextUtils.isEmpty(socketData)) && (socketData.getBytes().length != socketData.length())) { 9 ArrayList<String> list = new ArrayList<String>(); 10 Pattern p = Pattern.compile(regEx); 11 Matcher m = p.matcher(socketData); 12 while (m.find()) { 13 list.add(m.group(0)); 14 } 15 for(int i=0;i<list.size();i++){ 16 String oldStr = list.get(i); 17 String newStr = encoding(oldStr); 18 socketData = socketData.replaceFirst(oldStr, newStr); 19 } 20 } 21 return socketData; 22 23 } 24 /**主要处理字符串中汉字的编码,data必须是一个汉字或多个汉字相连的字符串形式*/ 25 static String encoding(String data){ 26 if(TextUtils.isEmpty(data)){ 27 return data; 28 }else{ 29 KTLog.e("data>>>转码前>>"+data);//test 30 int size = data.length(); 31 String temp = null; 32 byte[] arrays =null; 33 try { 34 arrays = (data+"1").getBytes(CCSParams.SocketParams.SOCKET_DATA_PARSE_FORMAT); 35 String[] strArrays = SocketUtils.byteArray2HexStr(arrays, true).split(" "); 36 StringBuffer strb = new StringBuffer(); 37 for(int i=0;i<size*2;i+=2){ 38 strb.append(‘%‘).append(strArrays[i]).append(‘%‘).append(strArrays[i+1]); 39 } 40 temp = strb.toString(); 41 } catch (UnsupportedEncodingException e) { 42 KTLog.e("encoding执行("+data+")异常", e); 43 } 44 return temp; 45 } 46 } 47 48 public static String byteArray2HexStr(byte[] bArray, boolean format) { 49 StringBuffer strb = null; 50 if (null != bArray) { 51 strb = new StringBuffer(bArray.length); 52 for (int i = 0; i < bArray.length; i++) { 53 String str = Integer.toHexString(0xFF & bArray[i]).trim(); 54 if (str.length() < 2) { 55 strb.append("0"); 56 } 57 strb.append(str); 58 if (format) { 59 strb.append(" "); 60 } 61 } 62 } else { 63 return null; 64 } 65 return strb.toString().trim(); 66 }
关于android.jar里的java.net.URLEncoder.encode()和jdk里的java.net.URLEncoder.encode()出现的问题
标签:
原文地址:http://www.cnblogs.com/enyu-smile/p/4442701.html