首页 > 代码库 > JAVA js的escape函数、解析用js encodeURI编码的字符串、utf8转gb2312的函数

JAVA js的escape函数、解析用js encodeURI编码的字符串、utf8转gb2312的函数

在使用webView时,如果url中参数有中文的话,拦截到的字符串就会类似这样的:http://api.letstar.cn/zq/news.html?id=20&cupName=%E6%B5%8B%E8%AF%957,那我如果想使用cupName怎么办呢?

	public static String escape(String src) {		int i;		int j;		StringBuffer tmp = new StringBuffer();		tmp.ensureCapacity(src.length() * 6);		for (i = 0; i < src.length(); i++) {			j = src.charAt(i);			 if (j < 256) {				tmp.append("%");				if (j < 16) tmp.append("0");				tmp.append(Integer.toString(j, 16));			}			else {				tmp.append("%u");				tmp.append(Integer.toString(j, 16));			}		}		return tmp.toString();	}

  

String str="K.A%C3%A4%C2%B8%C2%B4%C3%A6%C2%97%C2%B6%C3%A4%C2%BE%C2%9B%C3%A5%C2%BA%C2%94%C3%A5%C2%95%C2%86";			//str=escape(java.net.URLDecoder.decode(str,"utf-8"));//System.out.println(java.net.URLDecoder.decode(str,"utf-8"));			str= (java.net.URLDecoder.decode(str,"utf-8"));System.out.println(utf8Togb2312(str));

  解析:

	private static String utf8Togb2312(String str){	      StringBuffer sb = new StringBuffer();	      for(int i=0; i<str.length(); i++) {	          char c = str.charAt(i);	          switch (c) {	             case ‘+‘:	                 sb.append(‘ ‘);	             break;	             case ‘%‘:	                 try {	                      sb.append((char)Integer.parseInt(	                      str.substring(i+1,i+3),16));	                 }	                 catch (NumberFormatException e) {	                     throw new IllegalArgumentException();	                }	                i += 2;	                break;	             default:	                sb.append(c);	                break;	           }	      }	      // Undo conversion to external encoding	      String result = sb.toString();	      String res=null;	      try{	          byte[] inputBytes = result.getBytes("8859_1");	          res= new String(inputBytes,"UTF-8");	      }	      catch(Exception e){}	      return res;	}

  

JAVA js的escape函数、解析用js encodeURI编码的字符串、utf8转gb2312的函数