unicode编码与解码,代码如下
1 package com.fenqiguanjia.api.services; 2 3 /** 4 * Created by daixianjun on 2017/9/3. 5 */ 6 7 import org.apache.commons.lang.StringUtils; 8 9 public class UnicodeUtils { 10 11 12 /*** 13 * unicode 编码与解码 14 * v\u003d0; cookie2\u003d161b41dbe306333ef031fccf315df69a; 15 * 转成: v=0; cookie2=161b41dbe306333ef031fccf315df69a; 16 * @param unicode 17 * @return 18 */ 19 public static String unicode2String(String unicode){ 20 if(StringUtils.isBlank(unicode))return null; 21 StringBuilder sb = new StringBuilder(); 22 int i = -1; 23 int pos = 0; 24 25 while((i=unicode.indexOf("\\u", pos)) != -1){ 26 sb.append(unicode.substring(pos, i)); 27 if(i+5 < unicode.length()){ 28 pos = i+6; 29 sb.append((char)Integer.parseInt(unicode.substring(i+2, i+6), 16)); 30 } 31 } 32 33 if (pos < unicode.length()){ 34 sb.append(unicode.substring(pos)); 35 } 36 37 return sb.toString(); 38 } 39 40 public static String string2Unicode(String string) { 41 42 if(StringUtils.isBlank(string))return null; 43 StringBuffer unicode = new StringBuffer(); 44 45 for (int i = 0; i < string.length(); i++) { 46 47 // 取出每一个字符 48 char c = string.charAt(i); 49 50 // 转换为unicode 51 unicode.append("\\u" + Integer.toHexString(c)); 52 } 53 54 return unicode.toString(); 55 } 56 }