Http Post不显示内容

时间:2014-10-25 10:22:41

标签: c++ qt

所以我试图发帖到我的localhost以获得结果,如果成功与否,我遇到了问题。我认为它不是发送请求或只是没有得到页面的结果。我补充说:

QT += network

但它仍无效

void sendPost() {

QEventLoop eventLoop;
QNetworkAccessManager mgr;

QUrlQuery postData;
postData.addQueryItem("unm", "user");
postData.addQueryItem("pwd", "81238as");

QNetworkRequest request(QUrl(QString("http://localhost/login.php")));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

QNetworkReply *reply = mgr.post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
eventLoop.exec();

if (reply->error() == QNetworkReply::NoError) {

    QString data = reply->readAll();
        qDebug(data.toUtf8().constData());
        delete reply;
}
else {
    qDebug() << "Failure" <<reply->errorString();
    delete reply;
  }
}

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

您运行eventLoop以阻止所有应用,当您的经理完成时,您应该从eventLoop退出。下一个代码可以工作,但说实话,我总是用信号和插槽来做这个,所以我不知道使用QEventLoop是正确的方法。

试试这个:

#include <QObject>
//...
QEventLoop eventLoop;
QNetworkAccessManager mgr;

QUrlQuery postData;
postData.addQueryItem("unm", "user");
postData.addQueryItem("pwd", "81238as");

QNetworkRequest request(QUrl(QString("http://localhost/login.php")));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

QNetworkReply *reply = mgr.post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
QObject::connect(&mgr,SIGNAL(finished(QNetworkReply*)),&eventLoop,SLOT(quit()));
eventLoop.exec();

if (reply->error() == QNetworkReply::NoError) {

    QString data = reply->readAll();
        qDebug(data.toUtf8().constData());
        delete reply;
}
else {
    qDebug() << "Failure" <<reply->errorString();
    delete reply;
  }