因此,我尝试将其发布到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;
  }
}

谢谢你的时间。

最佳答案

您运行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;
  }

09-27 21:13