unsigned char ToHex(unsigned char x)
return x > 9 ? x + 55 : x + 48;
unsigned char FromHex(unsigned char x)
unsigned char y;
if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;
else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;
else if (x >= '0' && x <= '9') y = x - '0';
else assert(0);
return y;
std::string UrlEncode(const std::string& str)
std::string strTemp = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++)
if (isalnum((unsigned char)str[i]) ||
(str[i] == '-') ||
(str[i] == '_') ||
(str[i] == '.') ||
(str[i] == '~'))
strTemp += str[i];
else if (str[i] == ' ')
strTemp += "+";
strTemp += '%';
strTemp += ToHex((unsigned char)str[i] >> 4);
strTemp += ToHex((unsigned char)str[i] % 16);
return strTemp;
std::string UrlDecode(const std::string& str)
std::string strTemp = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++)
if (str[i] == '+') strTemp += ' ';
else if (str[i] == '%')
assert(i + 2 < length);
unsigned char high = FromHex((unsigned char)str[++i]);
unsigned char low = FromHex((unsigned char)str[++i]);
strTemp += high*16 + low;
else strTemp += str[i];
return strTemp;
补充知识:
C++中URL解码/编码
我就废话不多说了,大家还是直接看代码吧~
#include <iostream>
#include <string>
using namespace std;
char dec2hexChar(short int n) {
if (0 <= n && n <= 9) {
return char(short('0') + n);
else if (10 <= n && n <= 15) {
return char(short('A') + n - 10);
else {
return char(0);
short int hexChar2dec(char c) {
if ('0' <= c && c <= '9') {
return short(c - '0');
else if ('a' <= c && c <= 'f') {
return (short(c - 'a') + 10);
else if ('A' <= c && c <= 'F') {
return (short(c - 'A') + 10);
else {
return -1;
string escapeURL(const string& URL)
string result = "";
for (unsigned int i = 0; i < URL.length(); i++) {
char c = URL[i];
('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
c == '/' || c == '.'
result += c;
else {
int j = (short int)c;
if (j < 0) {
j += 256;
int i1, i0;
i1 = j / 16;
i0 = j - i1 * 16;
result += '%';
result += dec2hexChar(i1);
result += dec2hexChar(i0);
return result;
string deescapeURL(const string& URL) {
string result = "";
for (unsigned int i = 0; i < URL.length(); i++) {
char c = URL[i];
if (c != '%') {
result += c;
else {
char c1 = URL[++i];
char c0 = URL[++i];
int num = 0;
num += hexChar2dec(c1) * 16 + hexChar2dec(c0);
result += char(num);
return result;