urlencode.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * urlencode.cpp
  3. *
  4. * Created on: 2022年6月1日
  5. * Author: dingxy
  6. */
  7. #include "urlencode.h"
  8. #include "assert.h"
  9. unsigned char toHex(unsigned char c) {
  10. return c > 9? 'A'-10+c : '0'+c;
  11. }
  12. unsigned char fromHex(unsigned char h) {
  13. unsigned char c = 0;
  14. if(h>='A' && h<='Z') {
  15. c = h-'A'+10;
  16. }else if(h>='a' && h<='z') {
  17. c = h-'a'+10;
  18. } else if(h>='0' && h<='9') {
  19. c = h-'0';
  20. } else {
  21. }
  22. return c;
  23. }
  24. void encodeUrl(const string& str, string& result) {
  25. int len = str.length();
  26. for(int i=0; i<len; i++) {
  27. if(isalnum((unsigned char)str[i]) ||
  28. (str[i]=='.')||(str[i]=='-')||(str[i]=='*')||(str[i]=='_')) {
  29. result += str[i];
  30. } else if(str[i] == ' ') {
  31. result += '+';
  32. } else {
  33. result += '%';
  34. result += toHex((unsigned char)str[i] >> 4);
  35. result += toHex((unsigned char)str[i] & 0xF);
  36. }
  37. }
  38. }
  39. void encodeUrl(const char* str, string &result) {
  40. string tmp = str;
  41. encodeUrl(tmp, result);
  42. }
  43. void decodeUrl(const string& str, string &result) {
  44. result = "";
  45. int len = str.length();
  46. for(int i=0; i<len; i++) {
  47. if((str[i]=='.')||(str[i]=='-')||(str[i]=='*')||(str[i]=='_')) {
  48. result += str[i];
  49. } else if(str[i] == '+') {
  50. result += ' ';
  51. } else if(str[i] == '%') {
  52. assert(i+2 < len);
  53. unsigned char high = fromHex((unsigned char)str[++i]);
  54. unsigned char low = fromHex((unsigned char)str[++i]);
  55. result += ((high<<4) | low);
  56. } else if(isalnum((unsigned char)str[i])){
  57. result += str[i];
  58. } else {
  59. }
  60. }
  61. }
  62. void decodeUrl(const char* str, string &result) {
  63. string tmp = str;
  64. decodeUrl(tmp, result);
  65. }