QHttp在Qt5中不可用



我注意到QHttp类在Qt5中不再可用,我一直收到一条错误消息,说我需要使用QNetworkAccessManager来完成此操作。

有没有办法在Qt5中访问这个类?

在Qt 5中使用QNetworkAccessManager。您可以使用事件循环等待,直到回复完成,然后读取可用字节:

QString My_class::My_Method()
{
   QNetworkAccessManager manager;
   QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(myURL)));
   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);
   delete reply;
   return str;
}

您也可以通过将QNetworkAccessManagerfinished信号连接到一个插槽来以异步方式进行:

connect(&manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onFinished(QNetworkReply*)));

并在那里读取数据:

void onFinished(QNetworkReply* reply)
{
   if (reply->error() == QNetworkReply::NoError)
   {
       QByteArray bts = reply->readAll();
       ...
   }
}

这是一个简单的HTTP帖子(我使用的是Qt 5.3.2)

int Connection::postRequest(QString requestType, QUrl params){
    QString params_array = params.query();
    QNetworkRequest request(user->url);
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(params_array.size()));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QEventLoop waitLoop;
    QNetworkAccessManager* connection = new QNetworkAccessManager(/*`this` can also be passed*/);
    QNetworkReply* reply = connection->post(request, params_array.toUtf8());
    QObject::connect(reply, SIGNAL(finished()), &waitLoop, SLOT(quit()));
    waitLoop.exec();
    int errorCode = reply->error();
    if (errorCode != 0){
        // Show Error Message
    }
    else{
        // Parse "reply"
    }
    delete reply;
    delete connection;
    return errorCode;
}

假设您不需要维护庞大的代码库,正确的方法是使用新的QNetworkAccessManager类。

相关内容

  • 没有找到相关文章

最新更新