! * ' ( ) ; : @ & = + $ , / ? % # [ ] — 特定語境有特殊含義,通常需編碼。A-Z a-z 0-9 - _ . ~ — 無需編碼。%XX 形式編碼 (UTF-8 位元組逐個轉義)。+ 或 %20;路徑段建議用 %20。#include <string>
#include <cctype>
#include <cstdlib>
#include <vector>
std::string UrlEncode(const std::string& input) {
static const char* hex = "0123456789ABCDEF";
std::string output;
output.reserve(input.size() * 3); // 預估空間
for (unsigned char c : input) {
// 非保留字元 (RFC 3986 unreserved) 直接輸出
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
output += c;
}
// 空格編為 %20 (路徑段標準);若為 query string 可改 '+'
else if (c == ' ') {
output += "%20";
}
// 其他字元進行 %XX 編碼
else {
output += '%';
output += hex[c >> 4];
output += hex[c & 0xF];
}
}
return output;
}
std::string UrlDecode(const std::string& input) {
std::string output;
output.reserve(input.size());
for (size_t i = 0; i < input.size(); ++i) {
if (input[i] == '%' && i + 2 < input.size()) {
char h1 = input[i + 1];
char h2 = input[i + 2];
if (std::isxdigit(h1) && std::isxdigit(h2)) {
int value = (std::isdigit(h1) ? h1 - '0' : std::toupper(h1) - 'A' + 10) * 16
+ (std::isdigit(h2) ? h2 - '0' : std::toupper(h2) - 'A' + 10);
// RFC 3986: 非保留字元解碼後可直接輸出;保留字元保持編碼形式
// 這裡採用寬鬆策略:全部解碼,由上層應用決定是否需保留編碼
output += static_cast<char>(value);
i += 2;
continue;
}
}
// '+' 在 query string 中代表空格
if (input[i] == '+') output += ' ';
else output += input[i];
}
return output;
}
unsigned char 避免負數擴展: char 有符號性實現定義,位運算前轉為 unsigned char 確保正確。sprintf 開銷,效能更高。reserve(): 減少字串重新分配。i+2 不越界,遇到非法 % 序列保守輸出原字元。std::toupper 處理 %2f / %2F 同義。int main() {
std::vector<std::pair<std::string, std::string>> tests = {
{"Hello World!", "Hello%20World%21"},
{"中文測試", "%E4%B8%AD%E6%96%87%E6%B8%AC%E8%A9%A6"}, // UTF-8 字節編碼
{"a+b=c", "a%2Bb%3Dc"},
{"path/to/file", "path%2Fto%2Ffile"},
{"~user/home", "~user%2Fhome"}
};
for (auto& [raw, expected] : tests) {
std::string enc = UrlEncode(raw);
std::string dec = UrlDecode(enc);
bool ok = (enc == expected && dec == raw);
std::cout << (ok ? "[PASS] " : "[FAIL] ")
<< "raw=" << raw
<< " enc=" << enc
<< " dec=" << dec << '\n';
}
return 0;
}
EncodePathSegment / EncodeQueryValue。application/x-www-form-urlencoded 表單提交規則:空格→+,其餘同 RFC 3986。URL 編碼看似簡單,細節決定正確性。上述實作遵循 RFC 3986 核心規則,涵蓋保留/非保留字元判斷、UTF-8 多位元組支援、邊界防護,適合嵌入式/無依賴環境。正式專案建議直接採用標準庫或成熟開源庫,避免重複造輪子引入漏洞。