Qnetworkrequest Header Example For Essay

There are many APIs on the web that accept JSON requests and reply using JSON. An example for this can be most of Google’s API services. For example if you are writing a Qt application that needs JSON interaction with a Google API (such as Google Webmaster API) you can easily send requests and receive responses if you follow these steps.





First of all make sure that your Qt project is using network module by adding the following line to your .pro file.

QT += network

Next you have to add QtNetwork header files to your source code using the line below.

#include <QtNetwork>

Now you need to create a request using the specific URL for that web service or API.

QNetworkRequest request(QUrl(“http://example.com/exampleapi”));

You have to set the request header content type as seen below:

request.setHeader(QNetworkRequest::ContentTypeHeader, “application/json”);

Then you have to create your JSON request. (What is shown here is just an example and not a real JSON request.)

QJsonObject json;

body.insert(“item1”, “value1”);

body.insert(“item2”, “value2”);





Now you have to create a Network Access object which will help with sending the request.

QNetworkAccessManager nam;

And send (POST) your JSON request. Result will be saved in a QNetworkRply

QNetworkReply *reply = nam.post(request, QJsonDocument(json).toJson());

You have to wait for the response from server.

while(!reply->isFinished())

{

qApp->processEvents();

}

When server sends you the response, you have to store it like this:

QByteArray response_data = reply->readAll();

Assuming that the response is a JSON object you can change its format like this:

QJsonDocument json = QJsonDocument::fromJson(response_data);

One last thing to note is that you have to clean up the reply object by yourself using the line below:

reply->deleteLater();





Related

Qt5 Tutorial QNetworkAccessManager - Downloading Files - 2018




bogotobogo.com site search:





QNetworkAccessManager / QNetworkRequest - Downloading Files

In this tutorial, we will learn how to download a file using QNetworkAccessManager.

Note: Qt5 document

The QFtp, QUrlInfo, QHttp classes are not public anymore (QHttp has been discouraged since Qt 4.7). Use QNetworkAccessManager instead to avoid binary breaks in the future. Programs that require raw FTP/HTTP streams, can use the compatibility add-ons QtFtp and QtHttp which provides the QFtp and QHttp classes as they existed in Qt 4.


We'll start with Qt Console Application.



First, we need to add network module to our project file, QHpptDownload.pro:

QT += core QT += network QT -= gui TARGET = QHttpDownload CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp

Then, we want to create a new class called Downloader.

In general, this tutorial is almost the same with the one of my C++ tutorials Sockets - Server and Client using Qt : Http Download. However, this tutorial is using NetworkAccessManager instead of QHttp as recommended by Qt5.

Now, let's work on our header file, downloader.h.

We want to include <QNetworkAccessManager>, <QNetworkRequest>, <QNetworkReply>, <QUrl>, <QDateTime>, <QFile>, and <QDebug>. Then, we need to put a reference to QNetworkAccessManager as a private member.

Also, we need to emit a signal, replyFinished().

We want to declare a public function doDownload().

#ifndef DOWNLOADER_H #define DOWNLOADER_H #include <QObject> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> #include <QDateTime> #include <QFile> #include <QDebug> class Downloader : public QObject { Q_OBJECT public: explicit Downloader(QObject *parent = 0); void doDownload(); signals: public slots: void replyFinished (QNetworkReply *reply); private: QNetworkAccessManager *manager; };

Lets move on to the implementation:

The whole process will be kick off by doDownload():

void Downloader::doDownload() { manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); manager->get(QNetworkRequest(QUrl("http://bogotobogo.com"))); }

Here is the description for QNetworkAccessManager from Qt 5 document.

The QNetworkAccessManager class allows the application to send network requests and receive replies.

The Network Access API is constructed around one QNetworkAccessManager object, which holds the common configuration and settings for the requests it sends. It contains the proxy and cache configuration, as well as the signals related to such issues, and reply signals that can be used to monitor the progress of a network operation. One QNetworkAccessManager should be enough for the whole Qt application.

Once a QNetworkAccessManager object has been created, the application can use it to send requests over the network. A group of standard functions are supplied that take a request and optional data, and each return a QNetworkReply object. The returned object is used to obtain any data returned in response to the corresponding request.

The doDownload() function is called from main(), and the slot replyFinished() is the place we do whatever we want with the QNetworkReply *:

void Downloader::replyFinished (QNetworkReply *reply) { if(reply->error()) { qDebug() << "ERROR!"; qDebug() << reply->errorString(); } else { qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString(); qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString();; qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); QFile *file = new QFile("C:/Qt/Dummy/downloaded.txt"); if(file->open(QFile::Append)) { file->write(reply->readAll()); file->flush(); file->close(); } delete file; } reply->deleteLater(); }

For more information on enums such as
QNetworkRequest::Attribute,
QNetworkRequest::CacheLoadControl,
and QNetworkRequest::KnownHeaders,
visit http://qt-project.org/doc/qt-5.0/qtnetwork/qnetworkrequest.html.



Here are the files used in this tutorial.


main.cpp:

#include <QCoreApplication> #include "downloader.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Downloader d; d.doDownload(); return a.exec(); }

downloader.h:

#ifndef DOWNLOADER_H #define DOWNLOADER_H #include <QObject> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> #include <QDateTime> #include <QFile> #include <QDebug> class Downloader : public QObject { Q_OBJECT public: explicit Downloader(QObject *parent = 0); void doDownload(); signals: public slots: void replyFinished (QNetworkReply *reply); private: QNetworkAccessManager *manager; }; #endif // DOWNLOADER_H

downloader.cpp:

#include "downloader.h" Downloader::Downloader(QObject *parent) : QObject(parent) { } void Downloader::doDownload() { manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); manager->get(QNetworkRequest(QUrl("http://bogotobogo.com"))); } void Downloader::replyFinished (QNetworkReply *reply) { if(reply->error()) { qDebug() << "ERROR!"; qDebug() << reply->errorString(); } else { qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString(); qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString(); qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); QFile *file = new QFile("C:/Qt/Dummy/downloaded.txt"); if(file->open(QFile::Append)) { file->write(reply->readAll()); file->flush(); file->close(); } delete file; } reply->deleteLater(); }

If we run the code:

"text/html" "Sun Dec 23 00:11:02 2012" 0 200 "OK"

If not successful. Otherwise, it will print our error message from reply->error().

For extended version using UI and QProgressDialog, please visit Http File Download with UI and QProgressDialog.








Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong



Comments

Leave a Reply

Your email address will not be published. Required fields are marked *