Qttt中没有QHttp

时间:2014-10-03 13:54:47

标签: c++ qt qt5 qnetworkaccessmanager qhttp

我注意到Qt5中不再提供QHttp类,并且我不断收到一条错误消息,指出我需要使用QNetworkAccessManager来执行此操作。

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

3 个答案:

答案 0 :(得分:6)

在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;

}

您也可以通过将finished的{​​{1}}信号连接到广告位来以异步方式执行此操作:

QNetworkAccessManager

并在那里读取数据:

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

答案 1 :(得分:4)

这是一个简单的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;
}

答案 2 :(得分:1)

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