URLEncode:是指针对网页url中的中文字符的一种编码转化方式,最常见的就是Baidu、Google等搜索引擎中输入中文查询时候,生成经过Encode过的网页URL。
URLEncode的方式一般有两种,一种是传统的基于GB2312的Encode(Baidu、Yisou等使用),另一种是基于UTF-8的Encode(Google、Yahoo等使用)。

C++实现:

GB2312的Encode:

 

 
  
  1. std::string CStringUtil::URLEncode( const string &sIn )  
  2. {  
  3.     string sOut;  
  4.     forsize_t ix = 0; ix < sIn.size(); ix++ )  
  5.     {        
  6.         BYTE buf[4];  
  7.         memset( buf, 0, 4 );  
  8.         if( isalnum( (BYTE)sIn[ix] ) )  
  9.         {        
  10.             buf[0] = sIn[ix];  
  11.         }  
  12.         //else if ( isspace( (BYTE)sIn[ix] ) ) //貌似把空格编码成%20或者+都可以  
  13.         //{  
  14.         //    buf[0] = '+';  
  15.         //}  
  16.         else 
  17.         {  
  18.             buf[0] = '%';  
  19.             buf[1] = toHex( (BYTE)sIn[ix] >> 4 );  
  20.             buf[2] = toHex( (BYTE)sIn[ix] % 16);  
  21.         }  
  22.         sOut += (char *)buf;  
  23.     }  
  24.     return sOut;  
  25.  
  26. }  
  27.  
  28. std::string CStringUtil::URLDecode( const string &sIn )  
  29. {  
  30.     string sOut;  
  31.     forsize_t ix = 0; ix < sIn.size(); ix++ )  
  32.     {  
  33.         BYTE ch = 0;  
  34.         if(sIn[ix]=='%')  
  35.         {  
  36.             ch = (fromHex(sIn[ix+1])<<4);  
  37.             ch |= fromHex(sIn[ix+2]);  
  38.             ix += 2;  
  39.         }  
  40.         else if(sIn[ix] == '+')  
  41.         {  
  42.             ch = ' ';  
  43.         }  
  44.         else 
  45.         {  
  46.             ch = sIn[ix];  
  47.         }  
  48.         sOut += (char)ch;  
  49.     }  
  50.     return sOut;  

2.UTF-8的Encode

先把字符串转为UTF-8编码。再调用以上函数。

stringToUTF8, UTF8Tostring

附:

一个查看编码结果的网址:http://tool.chinaz.com/Tools/URLEncode.aspx

“中文” GB2312的Encode:%d6%d0%ce%c4

“中文” UTF-8的Encode: %e4%b8%ad%e6%96%87