Reputation: 195
so am trying to post to my localhost
to get a result if it succeeded or not and I am having a problem. I think it's not sending the request or just not getting the result of the page. I added:
QT += network
but its still not working
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;
}
}
Thanks for your time.
Upvotes: 1
Views: 76
Reputation: 18504
You run eventLoop
so it blocks all your app, you should quit from eventLoop
when your manager is finished. Next code works but to be honest, I always do this with signals and slots so I don't know is usage of QEventLoop
is correct approach.
Try this:
#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;
}
Upvotes: 2