URLEncode與URLDecode總結與實現

weixin_33894992發表於2015-04-01

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 }

 

相關文章