萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 實現 URL Encode / Decode 完整代碼 (RFC 3986 相容)

URL 編碼規則速覽 (RFC 3986)

  • 保留字元 (保留用途): ! * ' ( ) ; : @ & = + $ , / ? % # [ ] — 特定語境有特殊含義,通常需編碼。
  • 非保留字元 (可直接使用): 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;
}

代碼關鍵點解析

  1. 使用 unsigned char 避免負數擴展: char 有符號性實現定義,位運算前轉為 unsigned char 確保正確。
  2. 查表法十六進制轉換: 避免 sprintf 開銷,效能更高。
  3. 預留空間 reserve(): 減少字串重新分配。
  4. 解碼時邊界檢查: 確保 i+2 不越界,遇到非法 % 序列保守輸出原字元。
  5. 大小寫不敏感解碼: 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;
}

生產環境建議

  • 直接使用成熟庫:cpp-httplib、Boost.URL (C++20)、curl (curl_easy_escape) — 經過充分測試、支援 Unicode 正規化。
  • 若需嚴格區分 路徑段 vs 查詢字串 編碼規則,請分別實作 EncodePathSegment / EncodeQueryValue。
  • 注意 application/x-www-form-urlencoded 表單提交規則:空格→+,其餘同 RFC 3986。

結語

URL 編碼看似簡單,細節決定正確性。上述實作遵循 RFC 3986 核心規則,涵蓋保留/非保留字元判斷、UTF-8 多位元組支援、邊界防護,適合嵌入式/無依賴環境。正式專案建議直接採用標準庫或成熟開源庫,避免重複造輪子引入漏洞。

copyright © 萬盛學電腦網 all rights reserved