gpt4 book ai didi

c++ - 如何将 QNetworkManager 用于 REST api?

转载 作者:行者123 更新时间:2023-11-30 01:48:41 24 4
gpt4 key购买 nike

我想创建一个通过 REST API 访问数据的类,例如:

class MeteoStation{
int getLatestTemperature();
int getLatestPessure();
private:
QNetworkManager nmng;
}

我该如何实现这些方法?通常我使用的是:

   int MeteoStation::getLatestTemperature(){    
...
QEventLoop eventLoop;
connect(&m_nam,SIGNAL(finished(QNetworkReply*)),&eventLoop,SLOT(quit()));
QNetworkReply *reply = m_nam.get( req );
eventLoop.exec();
reply->readAll()
...
}

但由于不推荐使用内部 QEventLoop,我应该如何查看响应属于谁?

MeteoStation::MeteoStation(){
connect(&nmam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(parseNetworkResponse(QNetworkReply*)));
}

void MeteoStation::parseNetworkResponse( QNetworkReply *finished )
{
QByteArray data = finished->readAll();
...

是的,保存类线程会很好。你是如何在你的代码中解决这个问题的?

使调用同步有多糟糕:

QNetworkRequest req(url);
QScopedPointer<QNetworkReply> reply(nam.get(req));

QTime timeout= QTime::currentTime().addSecs(10);
while( QTime::currentTime() < timeout && !reply->isFinished()){
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Failure" <<reply->errorString();
}
QByteArray data = reply->readAll();

最佳答案

我已经使用 QCoreApplication::processEvents() 解决了我的问题。响应在 ms 内,我能够实现接近 libcurl 的功能。

QNetworkRequest req(url);
QScopedPointer<QNetworkReply> reply(nam.get(req));

QTime timeout= QTime::currentTime().addSecs(10);
while( QTime::currentTime() < timeout && !reply->isFinished()){
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Failure" <<reply->errorString();
}
QByteArray data = reply->readAll();

关于c++ - 如何将 QNetworkManager 用于 REST api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30173038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com