首页 > 解决方案 > 从服务器 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 代码有什么问题或如何正确解释返回的字节字符串?

标签: 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"

推荐阅读