首页 >后端开发 >C++ >如何在 C 中稳健地编码和解码 URL?

如何在 C 中稳健地编码和解码 URL?

DDD
DDD原创
2024-12-04 08:48:12768浏览

How to Robustly Encode and Decode URLs in C  ?

C 中的 URL 编码和解码

问题:

C 中的 URL 编码和解码。有可用的可靠代码吗?

答案:

编码:

要解决 URL 编码问题,需要自定义一个C函数是基于C示例开发的代码:

#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);

        // Preserve alphanumeric and valid symbols
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
            continue;
        }

        // Percent-encode other characters
        escaped << uppercase;
        escaped << '%' << setw(2) << int((unsigned char) c);
        escaped << nouppercase;
    }

    return escaped.str();
}

解码:

实现解码函数是可选练习。

以上是如何在 C 中稳健地编码和解码 URL?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn