【发布时间】:2017-10-17 17:23:17
【问题描述】:
我使用 cpprestsdk 已经有一段时间了,直到今天还没有遇到过这个问题。我不确定发生了什么变化,但在调试了一段时间后,我对为什么会发生这种情况感到困惑。
将 utf-8 字符串转换为 wchar_t 以与其余调用一起使用时,出现错误“UTF-8 字符串字符永远不能以 10xxxxxx 开头”
引发此错误的 cpp 文件显示在第 280 行:https://github.com/Microsoft/cpprestsdk/blob/master/Release/src/utilities/asyncrt_utils.cpp
我将代码复制到我的程序中以尝试找出发生这种情况的原因,这就是我所拥有的: 注意:*tmp 是字符串向量的迭代器
`std::string str = *tmp->safe; //*tmp->safe == "WW-Department-Zone-OS"
const size_t sSize = str.size();
const char* const sData = str.data();
size_t result{ sSize };
for (size_t index = 0; index < sSize;) {
const char c{ sData[index++] };
if ((c & 0x40) == 0)
std::cout << "String starts with 10xxxxxx\n";
}`
使用断点时,我注意到当 'c' == '-' 字符及其后面的字符为 -40 'Ø' 时会引发错误。如果有人对为什么会发生这种情况有任何意见,将不胜感激。
【问题讨论】:
-
请发布minimal reproducible example(即,足以在您期望成功时发出此错误的调用)。此外,
c & 0x40检查第二高位,而不是最高位。 -
在调用之前,我需要将所有数据转换为 string_t/wchar_t,因此它甚至在调用之前就出错了。它在转换为 wchar_t 时被抛出。例如'PasswordName = utility::conversions::to_string_t(pwN);' pwN == "root-unknown-several appliance local logins-vROps Appliance Root" 由于函数很大,我就贴一个小例子。
-
只要示例遵循我给出的链接。我们可以按原样运行的完整的东西,但最小的东西,删除了所有不必要的代码,同时仍然是可验证的,因此我们可以获得相同的错误。您会发现,创建适当的 MCVE 会导致您在提出问题之前就发现答案。
-
pplx::task<void>Call(){ utility::string_t uri = L"rest.svc/Account", wPasswordName = L"", Safe=L""; string str="root-unknown-several appliance local logins-vROps Appliance Root"; string safe="WW-IES-GESM-NIX"; wPasswordName = utility::conversions::to_string_t(str); wSafe = utility::conversions::to_string_t(safe); json::value jAccount, jSafe; jSafe[L"Safe"]=json::value::string(wSafe); jSafe[L"accountName"]=json::value::string(wPasswordName); jAccount[L"account"]=jSafe; -
这里是电话
http_client client(L"myserver.com"); http_request reqeust(methods::Post); request.set_request_uri(uri); request.set_body(jAccount.serialize().c_sr()); request.headers().add(L"Authorization", token); request.headers().set_content(L"application/json"); return client.request(request).then([&](http_response response){ std::cout << response.status_code(); if(response.status_code() == status_codes::Created){ std::cout << "Success"; } });
标签: c++ rest utf-8 cpprest-sdk