C++实现url编码与解码
转载自:https://www.cnblogs.com/claireyuancy/p/6915447.html
稍加修改
url_code.h
/******************************************************************************
*
* Copyright (C), 2001-2005, Huawei Tech. Co., Ltd.
*
*******************************************************************************
* File Name : url_code.h
* Version : Initial Draft
* Author : sst
* Created : 2021/9/6
* Last Modified :
* Description : url_code.cpp header file
* Function List :
*
*
* History:
*
* 1. Date : 2021/9/6
* Author : sst
* Modification : Created file
*
******************************************************************************/
#ifndef __URL_CODE_H__
#define __URL_CODE_H__
/*==============================================*
* include header files *
*----------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
/*==============================================*
* constants or macros define *
*----------------------------------------------*/
/*==============================================*
* project-wide global variables *
*----------------------------------------------*/
/*==============================================*
* routines' or functions' implementations *
*----------------------------------------------*/
extern string UrlDecode(const string& str, string &dst);
extern string UrlEncode(const string& str, string &dst);
#endif /* __URL_CODE_H__ */
url_code.cpp
#include "url_code.h"
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 return 0;
return y;
}
string UrlEncode(const string& str, string &dst) {
dst = "";
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] == '~')) {
dst += str[i];
} else if(str[i] == ' ') {
dst += "+";
} else {
dst += '%';
dst += ToHex((unsigned char)str[i] >> 4);
dst += ToHex((unsigned char)str[i] % 16);
}
}
return dst;
}
string UrlDecode(const string& str, string &dst) {
dst = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++) {
if (str[i] == '+') {
dst += ' ';
} else if (i + 2 < length && str[i] == '%') {
unsigned char high = FromHex((unsigned char)str[++i]);
unsigned char low = FromHex((unsigned char)str[++i]);
dst += high*16 + low;
} else {
dst += str[i];
}
}
return dst;
}
test.cpp
#include "url_code.h"
int main(int argc, char *argv[])
{
string src, dst;
cin >> src;
UrlDecode(src, dst);
cout << dst << endl;
UrlEncode(dst, src);
cout << src << endl;
return 0;
}
输入:
%E6%B5%8B%E8%AF%95a%E7%94%A8%E6%88%B7
输出:
测试a用户
%E6%B5%8B%E8%AF%95a%E7%94%A8%E6%88%B7