添加项目文件。
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
#include "URLCodec.h"
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <cctype>
|
||||
|
||||
// 编码函数实现
|
||||
// 参考 Python 的 urllib.parse.quote 实现
|
||||
std::string urlcodec::url_encode(const std::string& input)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
for (const auto& ch : input)
|
||||
{
|
||||
// 保留字母、数字和部分符号
|
||||
if (std::isalnum(static_cast<unsigned char>(ch)) || ch == '-' || ch == '_' || ch == '.' || ch == '~')
|
||||
oss << ch;
|
||||
else // 其他字符进行百分号编码
|
||||
oss << '%' << std::uppercase << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(static_cast<unsigned char>(ch));
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
// 解码函数实现
|
||||
// 参考 Python 的 urllib.parse.unquote 实现
|
||||
bool urlcodec::url_decode(const std::string& input, std::string& output)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
size_t length = input.length();
|
||||
|
||||
for (size_t i = 0; i < length; ++i)
|
||||
{
|
||||
if (input[i] == '%')
|
||||
{
|
||||
if (i + 2 >= length)
|
||||
return false; // 错误:不完整的百分号编码
|
||||
std::string hex_str = input.substr(i + 1, 2);
|
||||
if (!std::isxdigit(hex_str[0]) || !std::isxdigit(hex_str[1]))
|
||||
return false; // 错误:无效的十六进制字符
|
||||
char decoded_char = static_cast<char>(std::stoi(hex_str, nullptr, 16));
|
||||
oss << decoded_char;
|
||||
i += 2; // 跳过已处理的两个字符
|
||||
}
|
||||
else
|
||||
oss << input[i];
|
||||
}
|
||||
output = oss.str();
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user