c++ - 在 C++ 中编码/解码 URL

标签 c++ urlencode urldecode percent-encoding

有人知道有什么好的 C++ 代码可以做到这一点吗?

最佳答案

前几天我遇到了这个问题的一半编码。对可用选项不满意,查看 this C sample code 后,我决定推出自己的 C++ url-encode 函数:

#include <cctype>
#include <iomanip>
#include <sstream>
#include <string>

using namespace std;

string url_encode(const string &value) {
    ostringstream escaped;
    escaped.fill('0');
    escaped << hex;

    for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
        string::value_type c = (*i);

        // Keep alphanumeric and other accepted characters intact
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
            continue;
        }

        // Any other characters are percent-encoded
        escaped << uppercase;
        escaped << '%' << setw(2) << int((unsigned char) c);
        escaped << nouppercase;
    }

    return escaped.str();
}

decode 函数的实现留给读者作为练习。 :P

关于c++ - 在 C++ 中编码/解码 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/154536/

相关文章:

java - Spring 启动 : @RequestParam in controller reads the request with '&' and '#' as empty

JavaScript 数组到 URL 编码 - obj 中的 wthis 数组

java - 是否有一个通用的 Java 库可以处理一组字符串的 URL 编码/解码?

c++ - std::getline 返回同一行的倍数

c++ - GLFW 设置窗口图标

c++ - 如何从C++中的字符串ID中提取int日、月和年

C# 解码路径上包含 %2F 的 URL,有什么方法可以指示 API 按原样发送 URL?

java - 字符串 url 编码两次,我无法获取初始字符串

python - django:如何将传入的 POST 数据作为类似文件的 obj 来使用以进行流处理

c++ - Valgrind 合法的 "possibly lost"字节示例