所以我试图发帖到我的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;
}
}
感谢您的时间。
答案 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;
}