我试图用Qt和C ++将HTTP请求的内容转换为QString变量
QNetworkAccessManager networkManager;
QUrl url("https://someurl.test.com/this-actually-exists");
QNetworkRequest request;
request.setUrl(url);
QNetworkReply* currentReply = networkManager.get(request); // GET
QString reply = QTextCodec::codecForMib(1015)->toUnicode(currentReply->readAll());
仍然,变量reply
似乎保持空白。显然,我误解了文档。我如何才能实现这一目标?
答案 0 :(得分:2)
您可以使用两种不同的方式,甚至以同步或异步方式执行此操作。异步方式是:
connect (&networkManager , SIGNAL(finished(QNetworkReply*)) ,this, SLOT(done(QNetworkReply*)));
networkManager.get(request);
您应该通过以下方式阅读连接到finished
信号的插槽中返回的回复中的内容:
void net::done(QNetworkReply * reply)
{
if (reply->error() == QNetworkReply::NoError)
{
data = QString(reply->readAll ());
}
else
{
data = QString(reply->errorString ());
}
}
同步方式如下:
QNetworkReply *reply = networkManager.get(request);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit()));
loop.exec();
QByteArray bts = reply->readAll();
QString str(bts);
这里使用事件循环等待答复完成,然后读取可用字节并获取字符串。
答案 1 :(得分:1)
我需要假设你正在运行一个带有事件循环的应用程序?如果没有,那就更难了......
如果是这样,请替换构建回复QString的最后一行:
connect(currentReply, SIGNAL(finished()), this, SLOT(gotAReply()));
然后你必须在你的班级中定义另一个方法作为一个插槽,一旦该回复被填满就会被触发:
void gotAReply()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
if (reply)
{
if (reply->error() == QNetworkReply::NoError)
{
QString replyText( reply->readAll() );
}
reply->deleteLater();
}
}
别忘了:对于Signals和Slot来说,你的类声明必须包含Q_OBJECT宏。