UrlEncodeHelper.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // UrlEncodeHelper.cpp
  3. // cocos2d_libs
  4. //
  5. // Created by zhuge on 2018/1/26.
  6. //
  7. #include "UrlEncodeHelper.h"
  8. unsigned char ToHex(unsigned char x) {
  9. return x > 9 ? x + 55 : x + 48;
  10. }
  11. unsigned char FromHex(unsigned char x) {
  12. unsigned char y;
  13. if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;
  14. else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;
  15. else if (x >= '0' && x <= '9') y = x - '0';
  16. else assert(0);
  17. return y;
  18. }
  19. string UrlEncodeHelper::url_encode(const string &str) {
  20. std::string strTemp = "";
  21. size_t length = str.length();
  22. for (size_t i = 0; i < length; i++)
  23. {
  24. if (isalnum((unsigned char)str[i]) ||
  25. (str[i] == '-') ||
  26. (str[i] == '_') ||
  27. (str[i] == '.') ||
  28. (str[i] == '~'))
  29. strTemp += str[i];
  30. else if (str[i] == ' ')
  31. strTemp += "+";
  32. else
  33. {
  34. strTemp += '%';
  35. strTemp += ToHex((unsigned char)str[i] >> 4);
  36. strTemp += ToHex((unsigned char)str[i] % 16);
  37. }
  38. }
  39. return strTemp;
  40. }
  41. string UrlEncodeHelper::url_decode(const string &str) {
  42. std::string strTemp = "";
  43. size_t length = str.length();
  44. for (size_t i = 0; i < length; i++)
  45. {
  46. if (str[i] == '+') strTemp += ' ';
  47. else if (str[i] == '%')
  48. {
  49. assert(i + 2 < length);
  50. unsigned char high = FromHex((unsigned char)str[++i]);
  51. unsigned char low = FromHex((unsigned char)str[++i]);
  52. strTemp += high*16 + low;
  53. }
  54. else strTemp += str[i];
  55. }
  56. return strTemp;
  57. }