最近由于项目需要,写了一个函数专门对URL里的中文参数行编码,网页那边是用的UTF-8编码集的,所以在编码之前必须把字符串转换成UTF-8的再进编码。

大家都知道在URL地址里是不可传中文字符的,因此如果你要URL地址里传带有中文字符的参数那就必须对它进行编码。其实编码是很简单的,只是将字符串中的每个字符转换成16进制的用%隔开就行了。注意我这个函数是UTF-8的,如果你需要其它编码集的可以自行修改,最重要的是明白它是怎样进行编码的。

  1. int URLEncode(LPCTSTR pszUrl, LPTSTR pszEncode, int nEncodeLen)
  2. {
  3. if( pszUrl == NULL )
  4. return 0;
  5. if( pszEncode == NULL || nEncodeLen == 0 )
  6. return 0;
  7. //定义变量
  8. int nLength = 0;
  9. WCHAR* pWString = NULL;
  10. TCHAR* pString = NULL;
  11. //先将字符串由多字节转换成UTF-8编码
  12. nLength = MultiByteToWideChar(CP_ACP, 0, pszUrl, -1, NULL, 0);
  13. //分配Unicode空间
  14. pWString = new WCHAR[nLength];
  15. //先转换成Unicode
  16. MultiByteToWideChar(CP_ACP, 0, pszUrl, -1, pWString, nLength);
  17. //分配UTF-8空间
  18. nLength = WideCharToMultiByte(CP_UTF8, 0, pWString, -1, NULL, 0, NULL, NULL);
  19. pString = new TCHAR[nLength];
  20. //Unicode转到UTF-8
  21. nLength = WideCharToMultiByte(CP_UTF8, 0, pWString, -1, pString, nLength, NULL, NULL);
  22. static char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  23. memset(pszEncode, 0, nEncodeLen/sizeof(TCHAR));
  24. for( int i = 0; i < nLength-1; i++ )
  25. {
  26. unsigned char c = pString[i];
  27. if( c > 0x20 && c < 0x7f ) // 数字或字母
  28. {
  29. *pszEncode++ = c;
  30. }
  31. else if( c == 0x20 ) // 包含空格
  32. {
  33. *pszEncode++ = '+';
  34. }
  35. else // 进行编码
  36. {
  37. *pszEncode++ = '%';
  38. *pszEncode++ = hex[c / 16];
  39. *pszEncode++ = hex[c % 16];
  40. }
  41. }
  42. //删除内存
  43. delete pWString;
  44. delete pString;
  45. return nLength;
  46. }

用法介绍:

TCHAR szText[] = TEXT("我爱你");

TCHAR szEncode[255];

URLEncode(szText, szEncode, sizeof(szEncode));

编码后的字符串就存储在szEncode数组中。

posted on 2011-09-07 22:59  aricgreen  阅读(1329)  评论(0)    收藏  举报