最近由于项目需要,写了一个函数专门对URL里的中文参数行编码,网页那边是用的UTF-8编码集的,所以在编码之前必须把字符串转换成UTF-8的再进编码。
大家都知道在URL地址里是不可传中文字符的,因此如果你要URL地址里传带有中文字符的参数那就必须对它进行编码。其实编码是很简单的,只是将字符串中的每个字符转换成16进制的用%隔开就行了。注意我这个函数是UTF-8的,如果你需要其它编码集的可以自行修改,最重要的是明白它是怎样进行编码的。
- int URLEncode(LPCTSTR pszUrl, LPTSTR pszEncode, int nEncodeLen)
- {
- if( pszUrl == NULL )
- return 0;
- if( pszEncode == NULL || nEncodeLen == 0 )
- return 0;
- //定义变量
- int nLength = 0;
- WCHAR* pWString = NULL;
- TCHAR* pString = NULL;
- //先将字符串由多字节转换成UTF-8编码
- nLength = MultiByteToWideChar(CP_ACP, 0, pszUrl, -1, NULL, 0);
- //分配Unicode空间
- pWString = new WCHAR[nLength];
- //先转换成Unicode
- MultiByteToWideChar(CP_ACP, 0, pszUrl, -1, pWString, nLength);
- //分配UTF-8空间
- nLength = WideCharToMultiByte(CP_UTF8, 0, pWString, -1, NULL, 0, NULL, NULL);
- pString = new TCHAR[nLength];
- //Unicode转到UTF-8
- nLength = WideCharToMultiByte(CP_UTF8, 0, pWString, -1, pString, nLength, NULL, NULL);
- static char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
- memset(pszEncode, 0, nEncodeLen/sizeof(TCHAR));
- for( int i = 0; i < nLength-1; i++ )
- {
- unsigned char c = pString[i];
- if( c > 0x20 && c < 0x7f ) // 数字或字母
- {
- *pszEncode++ = c;
- }
- else if( c == 0x20 ) // 包含空格
- {
- *pszEncode++ = '+';
- }
- else // 进行编码
- {
- *pszEncode++ = '%';
- *pszEncode++ = hex[c / 16];
- *pszEncode++ = hex[c % 16];
- }
- }
- //删除内存
- delete pWString;
- delete pString;
- return nLength;
- }
用法介绍:
TCHAR szText[] = TEXT("我爱你");
TCHAR szEncode[255];
URLEncode(szText, szEncode, sizeof(szEncode));
编码后的字符串就存储在szEncode数组中。
浙公网安备 33010602011771号