从服务器php脚本返回西班牙语字符时出现Qt编码错误



所以我一直在做一些关于使用CURL、Qt和服务器端PHP在ñcharcate周围看到的编码错误的测试。我终于得到了一个超级极简主义的例子,其中错误仅在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 "$datan";
?>

其中";上传.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 xC3xB1oxC3xB1o", "age" : 58} nn"

尼格人又一次被搞砸了。有人能告诉我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"

最新更新