#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";
{
Q_OBJECT
QNetworkAccessManager nam;
QNetworkReply *reply;
public:
Downloader
(QObject * p
=0): reply
(0) { connect(&nam,
SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
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) {
Downloader d;
d.run();
return app.exec();
}
#include "main.moc"
#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*,QAuthenticator*)),
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"
To copy to clipboard, switch view to plain text mode
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.
Bookmarks