对UTF-8和GB2312格式 URL进行解码

转自:http://blog.csdn.net/vincent_void/article/details/7739094

对UTF-8和GB2312格式 URL进行解码

新的系统编码格式是:UTF-8  
老的页面编码格式是: GB2312  
新的系统的URL参数(带中文) 提交到老的系统中,中文参数是乱码。


解决思路1,在新的系统中传递的时候使用JS进行解码,然后再编码。这种方案,和浏览器本身传参无区别。所以,在使用这种方案后,在老的系统中解码,依然解决不了问题。

简单写一下实现的伪代码

传参的时候,使用JS 编码:
[javascript]  view plain copy
  1. location.href="old.aspx?word="+encodeURI('中文')  

老的页面解码:
[csharp]  view plain copy
  1. Server.UrlDecode(Request["word"]);  

最终还是乱码。

最终看了一下编过的汉字:“中文”

UTF-8下:

JS编码过的如下:               %E4%B8%AD%E5%9B%BD

浏览器FORM提交的如下:%E4%B8%AD%E5%9B%BD

GB2312:

JS编码格式如下:              %E4%B8%AD%E5%9B%BD

浏览器FORM提交的如下:%D6%D0%B9%FA

说明,使用JS编码模式都是将字符串用UTF-8模式下编码。

如果这样子的话,那我使用JS编码传参,后台都采用UTF-8进行解码就可以了。(这种思路未测试,我自己使用的是思路2)

[csharp]  view plain copy
  1. HttpUtility.UrlDecode(strEncode, Encoding.UTF8); //判断编码格式 UTF-8  

解决思路2,

既然是解码的问题,那我就要针对传过来的的字符串进行判断,然后进行相应的格式进行解码。

(1).判断其编码格式。

(2).再解码。

代码如下:

[csharp]  view plain copy
  1. //string strEncode =Request["word"];  //解码的时候这样子获取参数是有问题的,这样获取参数,无论怎么转都是乱码。应用下面的这种方式  
[csharp]  view plain copy
  1. string strEncode =GetWord( Request.ServerVariables["QUERY_STRING"]);  
[csharp]  view plain copy
  1. if (IsUTF8(strEncode)) result = HttpUtility.UrlDecode(strEncode, Encoding.UTF8); //判断编码格式 UTF-8  
  2. lse result = HttpUtility.UrlDecode(strEncode, Encoding.GetEncoding("GB2312")); 判断编码格式 GB2312  

[csharp]  view plain copy
  1.     /// <summary>  
  2.     /// 获取word参数  
  3.     /// </summary>  
  4.     /// <param name="value"></param>  
  5.     /// <returns></returns>  
  6.     private string GetWord(string value)  
  7.     {  
  8.         if (string.IsNullOrEmpty(value)) return "";  
  9.         string[] array = value.Split('&');  
  10.         string strEncode = "";  
  11.         for (int i = 0; i < array.Length; i++)  
  12.         {  
  13.             if (array[i].IndexOf("word=") >= 0)  
  14.             {  
  15.                 strEncode = array[i].Replace("word=""");  
  16.                 break;  
  17.             }  
  18.         }  
  19.         return strEncode;  
  20.     }  
  21.   
  22.     /// <summary>  
  23.     /// 获取字符的字节  
  24.     /// </summary>  
  25.     /// <param name="url"></param>  
  26.     /// <returns></returns>  
  27.     private static byte[] GetUrlCodingToBytes(string url)  
  28.     {  
  29.         StringBuilder sb = new StringBuilder();  
  30.   
  31.         int i = url.IndexOf('%');  
  32.         while (i >= 0)  
  33.         {  
  34.             if (url.Length < i + 3)  
  35.             {  
  36.                 break;  
  37.             }  
  38.             sb.Append(url.Substring(i, 3));  
  39.             url = url.Substring(i + 3);  
  40.             i = url.IndexOf('%');  
  41.         }  
  42.   
  43.         string urlCoding = sb.ToString();  
  44.         if (string.IsNullOrEmpty(urlCoding))  
  45.             return new byte[0];  
  46.   
  47.         urlCoding = urlCoding.Replace("%"string.Empty);  
  48.         int len = urlCoding.Length / 2;  
  49.         byte[] result = new byte[len];  
  50.         len *= 2;  
  51.         for (int index = 0; index < len; index++)  
  52.         {  
  53.             string s = urlCoding.Substring(index, 2);  
  54.             int b = int.Parse(s, System.Globalization.NumberStyles.HexNumber);  
  55.             result[index / 2] = (byte)b;  
  56.             index++;  
  57.         }  
  58.         return result;  
  59.     }  
  60.   
  61.     /// <summary>  
  62.     /// 判断字符是否为UTF-8  
  63.     /// </summary>  
  64.     /// <param name="url"></param>  
  65.     /// <returns></returns>  
  66.     private static bool IsUTF8(string url)  
  67.     {  
  68.         byte[] buf = GetUrlCodingToBytes(url);  
  69.         int i;  
  70.         byte cOctets; // octets to go in this UTF-8 encoded character    
  71.         bool bAllAscii = true;  
  72.         long iLen = buf.Length;  
  73.         cOctets = 0;  
  74.         for (i = 0; i < iLen; i++)  
  75.         {  
  76.             if ((buf[i] & 0x80) != 0) bAllAscii = false;  
  77.   
  78.             if (cOctets == 0)  
  79.             {  
  80.                 if (buf[i] >= 0x80)  
  81.                 {  
  82.                     do  
  83.                     {  
  84.                         buf[i] <<= 1;  
  85.                         cOctets++;  
  86.                     }  
  87.                     while ((buf[i] & 0x80) != 0);  
  88.   
  89.                     cOctets--;  
  90.                     if (cOctets == 0)  
  91.                         return false;  
  92.                 }  
  93.             }  
  94.             else  
  95.             {  
  96.                 if ((buf[i] & 0xC0) != 0x80)  
  97.                     return false;  
  98.                 cOctets--;  
  99.             }  
  100.         }  
  101.         if (cOctets > 0)  
  102.             return false;  
  103.         if (bAllAscii)  
  104.             return false;  
  105.         return true;  
  106.     }  

2012-8-3 16:20 

 今天,遇到一个问题,MVC项目中,一个AJAX请求的问题,又是乱码。肯定又是编码的东西,搞的人难受。其实很简答,一个文本框,输入一个值。AJAX请求一下,看是否存在,如果存在就清空。看前任写的代码,


[javascript]  view plain copy
  1. function checkUnitName(unitName) {  
  2.            if (unitName != "") {  
  3.                $.get("/Manage/Product/CheckUnitName", { pUnitName: encodeURI(unitName) }, function (data) {  
  4.                    if (data == "0") {  
  5.                        alert("单位名称已经存在,请选择");  
  6.                        $("#UnitName").val("");  
  7.                    }  
  8.                });  
  9.            }  
  10.        }  


[csharp]  view plain copy
  1.      public static string UNEscape(string str)  
  2.         {  
  3.             string outstr = "";  
  4.             #region 老方法  
  5.             if (!string.IsNullOrEmpty(str))  
  6.             {  
  7.                 string[] strlist = str.Replace("%""").Split('u');  
  8.                 try  
  9.                 {  
  10.                     for (int i = 1; i < strlist.Length; i++)  
  11.                     {  
  12.                         //将unicode字符转为10进制整数,然后转为char中文字符  
  13.                         outstr += (char)int.Parse(strlist[i].Substring(0, 4), System.Globalization.NumberStyles.HexNumber);  
  14.                     }  
  15.                 }  
  16.                 catch (FormatException ex)  
  17.                 {  
  18.                     outstr = ex.Message;  
  19.                 }  
  20.             }  
  21.             #endregion  
  22.   
  23.             return outstr;  
  24.         }  

这个方法基本没派上用场,执行过后,返回为 空字符串。

其实就这一句话就搞定了。

[csharp]  view plain copy
  1. public static string UNEscape(string str)  
  2. {  
  3.     string outstr =  outstr = HttpUtility.UrlDecode(str, Encoding.UTF8);  
  4.     return outstr;  
  5. }  

问题点是:

AJAX乱码问题

 从网上查资料得知,
1、xtmlhttp 返回的数据默认的字符编码是utf-8, 
2、post方法提交数据默认的字符编码是utf-8, (get也是的,自己就是使用get方式)


因为我这个项目是使用GB2312的编码格式,AJAX (UTF-8)  的模式传到后台,就会出现乱码了。明白了其中的道理,问题就好解决了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值