웹서버에 요청한 데이터를 수신하는 예제
요청 URL: http://www.google.com
응답: <HTML><HEAD><meta http-equiv=\”content-type\” content=\”text/html;charset=utf-8\”>\n<TITLE>302 Moved</TITLE></HEAD><BODY>\n<H1>302 Moved</H1>\nThe document has moved\n<A HREF=\”http://www.google.co.kr/?gfe_rd=cr&dcr=0&ei=kJAFWv-uOsOe9AWf_oCoBQ\”>here</A>.\r\n</BODY></HTML>\r\n
예제 코드
main.cpp #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QNetworkReply> namespace Ui { class MainWindow; } class QNetworkReply; class QSslError; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void request(); private: Ui::MainWindow *ui; QNetworkReply *m_reply; QNetworkAccessManager m_nam; private slots: void authenticationRequired(QNetworkReply*, QAuthenticator*); void httpFinished(); #ifndef QT_NO_SSL void sslErrors(QNetworkReply*,const QList<QSslError> &errors); #endif }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_reply = 0;connect(&m_nam, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); #ifndef QT_NO_SSL connect(&m_nam, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); #endifrequest(); }MainWindow::~MainWindow() { delete ui; }void MainWindow::request() { QSslConfiguration config = QSslConfiguration::defaultConfiguration(); config.setProtocol(QSsl::TlsV1_2);const QUrl url = QUrl::fromUserInput("http://www.google.com");QNetworkRequest request(url); m_reply = m_nam.get(request);connect(m_reply, SIGNAL(finished()), this, SLOT(httpFinished())); }void MainWindow::authenticationRequired(QNetworkReply*, QAuthenticator *) { qDebug() << "MainWindow::authenticationRequired"; }void MainWindow::httpFinished() { m_reply = (QNetworkReply*)sender(); QString data = m_reply->readAll();qDebug() << "MainWindow::httpFinished" << " data:" << data; }#ifndef QT_NO_SSL void MainWindow::sslErrors(QNetworkReply *, const QList<QSslError> &errors) { QString errorString; foreach (const QSslError &error, errors) { if (!errorString.isEmpty()) errorString += '\n'; errorString += error.errorString(); } qDebug() << "MainWindow::sslErrors" << "error:" << errorString;m_reply->ignoreSslErrors(); } #endif