URLEncode与URLDecode总结与实现

时间:2024-12-05 19:05:26

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

代码实现:

 unsigned char CHAR_TO_HEX( unsigned char ch )
{
//0xa(10)转化为字符'A'(65),要加上55 //0x0(0)转化为字符'0'(48),要加上48
return (unsigned char)(ch > ? ch + : ch + );
} std::string URLEncode(const char* pSrc)
{
unsigned char chTemp;
std::string strDest; while (*pSrc)
{
chTemp = (unsigned char)*pSrc;
if ( (chTemp >= 'a' && chTemp <= 'z') || (chTemp >= 'A' && chTemp <= 'Z') || (chTemp >= '' && chTemp <= '')
|| strchr("-_.!~*'()", chTemp))
{
strDest += chTemp;
}
else if (chTemp == ' ')
{
*pDest++ = '+';
}
else
{
strDest += '%';
strDest += CHAR_TO_HEX( (unsigned char)(chTemp >> ) );
strDest += CHAR_TO_HEX( (unsigned char)(chTemp & 0x0f) );
}
++pSrc;
} return strDest;
}

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

代码实现:

 unsigned char* URLDecode(unsigned char* pSrc, std::string &strDest)
{
char szTemp[]; while (*pSrc)
{
memset(szTemp, '/0', );
if( *pSrc != '%' && *pSrc != ' ')
{
strDest += *pSrc++;
continue;
}
else if( *pSrc == ' ' )
{
strDest += '+';
continue;
}
//忽略%
++pSrc;
unsigned char cTmp = ; for (int k = ; k < && *pSrc; ++k, ++pSrc)    //例如:将%3f ---> 0x3f
{
if(*pSrc <= '')//0x30~0x39
{
cTmp |= (*pSrc & 0x0f) << ( - k) * ;
}
else if(*pSrc >= 'a')//0x61~7a
{
cTmp |= (*pSrc - 0x57) << ( - k) * ;
}
else//0x41~5a
{
cTmp |= (*pSrc - 0x37) << ( - k) * ;
}
}
strDest += cTmp;
}
return ;
}