1 std::string UrlEncode(const std::string& szToEncode) 2 { 3 std::string src = szToEncode; 4 char hex[] = "0123456789ABCDEF"; 5 string dst; 6 7 for (size_t i = 0; i < src.size(); ++i) 8 { 9 unsigned char cc = src[i]; 10 if (isascii(cc)) 11 { 12 if (cc == ‘ ‘) 13 { 14 dst += "%20"; 15 } 16 else 17 dst += cc; 18 } 19 else 20 { 21 unsigned char c = static_cast<unsigned char>(src[i]); 22 dst += ‘%‘; 23 dst += hex[c / 16]; 24 dst += hex[c % 16]; 25 } 26 } 27 return dst; 28 } 29 30 31 std::string UrlDecode(const std::string& szToDecode) 32 { 33 std::string result; 34 int hex = 0; 35 for (size_t i = 0; i < szToDecode.length(); ++i) 36 { 37 switch (szToDecode[i]) 38 { 39 case ‘+‘: 40 result += ‘ ‘; 41 break; 42 case ‘%‘: 43 if (isxdigit(szToDecode[i + 1]) && isxdigit(szToDecode[i + 2])) 44 { 45 std::string hexStr = szToDecode.substr(i + 1, 2); 46 hex = strtol(hexStr.c_str(), 0, 16); 47 //字母和数字[0-9a-zA-Z]、一些特殊符号[$-_.+!*‘(),] 、以及某些保留字[$&+,/:;[email protected]] 48 //可以不经过编码直接用于URL 49 if (!((hex >= 48 && hex <= 57) || //0-9 50 (hex >=97 && hex <= 122) || //a-z 51 (hex >=65 && hex <= 90) || //A-Z 52 //一些特殊符号及保留字[$-_.+!*‘(),] [$&+,/:;[email protected]] 53 hex == 0x21 || hex == 0x24 || hex == 0x26 || hex == 0x27 || hex == 0x28 || hex == 0x29 54 || hex == 0x2a || hex == 0x2b|| hex == 0x2c || hex == 0x2d || hex == 0x2e || hex == 0x2f 55 || hex == 0x3A || hex == 0x3B|| hex == 0x3D || hex == 0x3f || hex == 0x40 || hex == 0x5f 56 )) 57 { 58 result += char(hex); 59 i += 2; 60 } 61 else result += ‘%‘; 62 }else { 63 result += ‘%‘; 64 } 65 break; 66 default: 67 result += szToDecode[i]; 68 break; 69 } 70 } 71 return result; 72 }
在线测试工具:http://tool.chinaz.com/Tools/URLEncode.aspx
c++ encode decode
时间: 2024-09-30 04:15:52