星期二, 九月 23, 2008

UTF8 URL的字符串转换

网页常常是UTF8的,POST数据时,有中文的话,经常是%XX%XX%XX这种形式

BOOL ConvertStringToURLCoding(CString &strDest, const char* strUTF8, int iLength)
{
strDest.Empty();
CString strTemp;
int i = 0;
while(i < iLength)
{
if ((unsigned)strUTF8[i] <= (unsigned char)0x7f)
{ //字母和数字不转换

if ((strUTF8[i] >= '0' && strUTF8[i] <= '9') ||
(strUTF8[i] >= 'A' && strUTF8[i] <= 'Z') ||
(strUTF8[i] >= 'a' && strUTF8[i] <= 'z'))
{
strDest += (char)strUTF8[i];
}

else if (strUTF8[i] == ' ') //空格转换成+号
{
strDest += '+';
}

else
{
strTemp.Format("%%%02X", (unsigned char)strUTF8[i]); //其他标点符号
strDest += strTemp;
}
i++;
}
else
{ //汉字或者其他的uft8文字,每3个字节一转
strTemp.Format("%%%02X%%%02X%%%02X", (unsigned char)strUTF8[i],
(unsigned char)strUTF8[i + 1], (unsigned char)strUTF8[i + 2]);
strDest += strTemp;
i += 3;
}
}
if (i == 0)
{
return FALSE;
}
return TRUE;
}

没有评论: