URLEncode与URLDecode总结与实现

URLEncode:
  用于编码URL字符串,数字和字母保持不变,空格变为‘+‘,其他(如:中文字符)先转换为十六进制表示,然后在每个字节前面加一个标识符%,
例如:“啊”字 Ascii的十六进制是0xB0A1——>%B0%A1

代码实现:

 1 unsigned char CHAR_TO_HEX( unsigned char ch )
 2 {
 3     //0xa(10)转化为字符‘A‘(65),要加上55 //0x0(0)转化为字符‘0‘(48),要加上48
 4     return (unsigned char)(ch > 9 ? ch + 55: ch + 48);
 5 }
 6 
 7 std::string URLEncode(const char* pSrc)
 8 {
 9     unsigned char chTemp;
10     std::string strDest;
11 
12     while (*pSrc)
13     {
14         chTemp = (unsigned char)*pSrc;
15         if ( (chTemp >= a && chTemp <= z) || (chTemp >= A && chTemp <= Z) || (chTemp >= 0 && chTemp <= 9)
16             || strchr("-_.!~*‘()", chTemp))
17         {
18             strDest += chTemp;
19         }
20          else if (chTemp ==  )
21          {
22              *pDest++ = +;
23          }
24         else
25         {
26             strDest += %;
27             strDest += CHAR_TO_HEX( (unsigned char)(chTemp >> 4) );
28             strDest += CHAR_TO_HEX( (unsigned char)(chTemp & 0x0f) );
29         }
30         ++pSrc;
31     }
32 
33     return strDest;
34 }

 

URLDecode:
  用于解码已编码的URL 字符串,解码方式与URLEncode相反

代码实现:

 1 unsigned char* URLDecode(unsigned char* pSrc, std::string &strDest)
 2 {
 3     char szTemp[2];
 4 
 5     while (*pSrc)
 6     {
 7         memset(szTemp, /0, 2 );
 8         if( *pSrc != % && *pSrc !=  )
 9         {
10             strDest += *pSrc++;
11             continue;
12         }
13         else if( *pSrc ==   )
14         {
15             strDest += +;
16             continue;
17         }
18         //忽略%
19         ++pSrc;
20         unsigned char cTmp = 0;
21 
22         for (int k = 0; k < 2 && *pSrc; ++k, ++pSrc)    //例如:将%3f ---> 0x3f
23         {
24             if(*pSrc <= 9)//0x30~0x39
25             {
26                 cTmp |= (*pSrc & 0x0f) << (1 - k) * 4;
27             }
28             else if(*pSrc >= a)//0x61~7a
29             {
30                 cTmp |= (*pSrc - 0x57) << (1 - k) * 4;
31             }
32             else//0x41~5a
33             {
34                 cTmp |= (*pSrc - 0x37) << (1 - k) * 4;
35             }
36         }
37         strDest += cTmp;
38     }
39     return 0;
40 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。