c++ 11 URL转码
时间: 2023-08-05 16:07:54 浏览: 162
C++11 引入了 `std::codecvt` 类来处理字符编码转换,其中包括 URL 转码。下面是一个使用 `std::codecvt` 类进行 URL 转码的示例代码:
```c++
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> utf32conv;
std::string url_encode(const std::string& value) {
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;
std::wstring wstr = utf32conv.from_bytes(value);
std::u16string u16str = utf16conv.to_bytes(wstr);
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> utf8conv;
std::string utf8str = utf8conv.to_bytes(u16str);
std::string escaped;
for (auto&& c : utf8str) {
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped += c;
}
else if (c == ' ') {
escaped += "+";
}
else {
escaped += "%" + std::to_string((int)(unsigned char)c);
}
}
return escaped;
}
int main() {
std::string url = "https://www.example.com/path/to/file?param1=value1¶m2=value2";
std::cout << url_encode(url) << std::endl; // Output: https%3A%2F%2Fwww.example.com%2Fpath%2Fto%2Ffile%3Fparam1%3Dvalue1%26param2%3Dvalue2
return 0;
}
```
此代码使用 `std::codecvt_utf8_utf16` 将 UTF-8 编码的字符串转换为 UTF-16 编码的字符串,然后使用 `std::codecvt_utf8` 将 UTF-16 编码的字符串转换为 UTF-8 编码的字符串。最后,它会将非字母数字字符转换为其十六进制表示,并将空格转换为加号符。
阅读全文