qt - 从服务器 php 脚本返回西班牙语字符时出现 Qt 编码错误
问题描述
所以我一直在做一些关于我在使用 CURL、Qt 和服务器端 PHP 的字符周围看到的编码错误的测试。我终于得到了一个超级简约的例子,错误只出现在 Qt 端。也许有人可以帮助我。
Qt代码如下:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString address = "http://localhost/api_test/test.php";
QUrl url(address);
QNetworkAccessManager manager;
QNetworkRequest request(url);
QNetworkReply *reply = manager.post(request, QByteArray());
QObject::connect(reply, &QNetworkReply::finished, QCoreApplication::quit);
a.exec();
if(reply->error() == QNetworkReply::NoError){
qDebug() << "The output";
qDebug() << QString(reply->readAll()).toUtf8();
}
else{
qDebug() << reply->error() << reply->errorString();
}
delete reply;
return 0;
}
在服务器端,test.php 如下:
<?php
$data = file_get_contents("uploaded.json");
echo "$data\n";
?>
其中“uploaded.json”是一个纯文本文件,其中包含
{"name" : "Ariel ñoño", "age" : 58}
curl 命令现在按预期工作
ariel@ColoLaptop:/home/web/api_test$ curl http://localhost/api_test/test.php
{"name" : "Ariel ñoño", "age" : 58}
但是当我运行 Qt 应用程序时,会发生这种情况:
The output
"{\"name\" : \"Ariel \xC3\xB1o\xC3\xB1o\", \"age\" : 58} \n\n"
ñ 字符再次被搞砸了。谁能告诉我 Qt 代码有什么问题或如何正确解释返回的字节字符串?
解决方案
“ñ” 是 unicode 文本,所以使用toUtf8()
不会成功。您必须使用 QTextDecoder
qDebug() << "The output";
QTextCodec* codec = QTextCodec::codecForLocale();
QTextDecoder* decoder = codec->makeDecoder();
QString text = decoder->toUnicode(reply->readAll());
qDebug() << text;
输出:
The output
"{\"name\" : \"Ariel ñoño\", \"age\" : 58}\n"
推荐阅读
- javascript - 在网站上看不到已发布的数据和图像,缺少什么?
- ios - 无法在 iOS swift 中将 base64string 解码为 uiimage 但在 android 中工作正常
- java - 使用 liquibase 删除数据库中的表不起作用
- c++ - cpp文件中定义的模板函数?
- winapi - 为什么在记事本窗口中输入时鼠标光标会消失,但在浏览器或 cmd 中却没有?哪些 Win API 函数显示它以及如何显示它?
- python - 如何删除缺少列名和数据的列
- python - 删除 Pandas Dataframe 中的整个列表行 - 如果列表包含元素(在这种情况下是一两张卡片)
- javascript - NodeJS:服务器返回“没有当前用户”。尝试在服务器端引用 ID 令牌时
- xcode - Xcode 12.3:无法为 com.me.myapp 重新创建协调器
- typescript - 如何访问带有空格的对象变量?打字稿