PDA

View Full Version : How to use QNetworkAccesManager ??



sliverTwist
28th March 2013, 10:22
Is there any tutorials or example for how to use QNetworkAccessManager with QAuthenticator and QNetworkRequest??
My application contains a step where the user fill in his login and password and connect to a server .
I didn't find too much on this subject on the web .Any help please ??

ChrisW67
29th March 2013, 01:14
It's about 5 lines of code.

Connect QNetworkAccessManager::authenticationRequired() to a slot. When the slot is called insert the user name and password matching the requesting site into the supplied QAuthenticator using setUser() and setPassword(). Job done.

sliverTwist
29th March 2013, 07:00
It's about 5 lines of code.

Connect QNetworkAccessManager::authenticationRequired() to a slot. When the slot is called insert the user name and password matching the requesting site into the supplied QAuthenticator using setUser() and setPassword(). Job done.
Please could you give me a code example which is verified because i tried that and didn't work for me.

ChrisW67
30th March 2013, 06:00
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QAuthenticator>
#include <QDebug>

static const QUrl url("http://test-host/");
static const char *user = "user";
static const char *password = "password";

class Downloader: public QObject
{
Q_OBJECT

QNetworkAccessManager nam;
QNetworkReply *reply;

public:
Downloader(QObject * p=0): reply(0) {
connect(&nam,
SIGNAL(authenticationRequired(QNetworkReply*,QAuth enticator*)),
SLOT(authRequired(QNetworkReply*,QAuthenticator*)) );
}

void run() {
QNetworkRequest req(url);
reply = nam.get(req);
connect(reply, SIGNAL(finished()), SLOT(done()));
}

public slots:
void authRequired(QNetworkReply *reply, QAuthenticator *authenticator) {
qDebug() << Q_FUNC_INFO << authenticator->realm();
// get user name and password from user for authenticator->realm()
// if (not cancelled) set the details otherwise don't
authenticator->setUser(user);
authenticator->setPassword(password);
}

void done() {
qDebug() << reply->readAll();
qApp->quit();
}
};

int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
Downloader d;
d.run();
return app.exec();
}

#include "main.moc"


Please be aware that this is how you handle the web server requesting authentication. This has nothing to do with handling web-applications requesting credentials: each of those is different but generally some form of HTML form.