【问题标题】:URL Encoding an Extended ASCII std::string in C++在 C++ 中对扩展 ASCII std::string 进行 URL 编码
【发布时间】:2018-03-20 16:45:26
【问题描述】:

我有一个 std::string 填充扩展 ASCII 值(例如 čáě)。我需要对这个字符串进行 URL 编码,以便 JavaScript 使用DecodeURIComponent 进行解码。

我尝试将其转换为 UTF-16,然后通过 windows-1252 代码点转换为 UTF-8,但由于没有足够的示例用于 MultiByteToWideCharWideCharToMultiByte 函数,因此无法这样做。

我在 Windows 10 64 位上使用 MSVC-14.0 进行编译。

如何至少遍历最终 UTF-8 字符串的各个字节以进行 URL 编码?

谢谢

【问题讨论】:

  • 扩展 ASCII 意义不大。文本使用一种特定的字符编码进行编码,要么一直使用相同的字符(几乎总是首选),要么是操作系统/用户/进程/线程的当前字符。那么它在你的程序中是什么? (如果您的程序使用字符串文字,那么答案就是您告诉编译器用作目标字符集的那个。)

标签: javascript c++ windows urlencode extended-ascii


【解决方案1】:

您可以使用MultiByteToWideChar将字符串转换为UTF-16,然后对字符一一编码。

示例代码:

std::string readData = "Extended ASCII characters (ěščřžýáíé)";
int size = MultiByteToWideChar(
    1252, //1252 corresponds with windows-1252 codepoint
    0,
    readData.c_str(),
    -1, //the string is null terminated, no need to pass the length
    NULL,
    0
);
wchar_t* wchar_cstr = new wchar_t[size];
MultiByteToWideChar(
    1252,
    0,
    readData.c_str(),
    -1,
    wchar_cstr,
    size
);
std::stringstream encodeStream;
for(uint32_t i = 0; i < size; i++){
    wchar_t wchar = wchar_cstr[i];
    uint16_t val = (uint16_t) wchar;
    encodeStream << "%" << std::setfill('0') << std::setw(2) << std::hex << val;
}
delete[] wchar_cstr;

std::string encodedString = encodeStream.str(); // the URL encoded string

虽然这确实对基本的 ASCII 字符 (

【讨论】:

  • 这不是标准的 C++,而是 Windows API。
【解决方案2】:

我设法用非常简单的代码做到了。 下面是从文件读取的 JSON 转换为 URL 并发送到外部网站以显示 JSON 中的语法错误的示例(在 MS/Windows 上测试):

void EncodeJsonFileTextAndSendToExternalWebSiteToShowSyntaxErrors (const std::string &jsonTxt)
{
        std::stringstream encodeStream;
        for (char c : jsonTxt)
        {
            if (c>='0' && c<='9' || c>='a' && c<='z' || c>='A' && c<='Z' || strchr("{}();",c))
                encodeStream << c;
            else
                encodeStream << "%" << std::setfill('0') << std::setw(2) << std::hex << (int)c;
        }
        std::string url = "cmd /c start https://jsonlint.com/?json=" + encodeStream.str();
        system(url.c_str());
}

它会自动打开这样的网络浏览器:https://jsonlint.com/?json={%0a%22dataset%20name%22%3a%20%22CIHP%22%0alabel%2017%0a}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2013-11-09
    相关资源
    最近更新 更多