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

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

DDD
发布: 2024-12-04 08:48:12
原创
767 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板