Making HTTP requests in Qt

I am new to Qt . I installed Qt for VS2008 and integrated it with my VS2010 . I just want to know how to make HTTP requests. I read about QtNetwork , but QtHttp is obselete.

I also know about libcurl and curlpp , but I have problems installing it and working with Qt.

What do you recommend, QtNetwork or curlpp ? If QtNetwork , can you give me a sample function or piece of code (and which class to use). If curlpp (libcurl) , can you tell me somewhere where I can find the steps to install it for Qt (or kindly explain)?

Thank you very much.

+4
source share
2 answers

libcurl and curlpp are great libraries, but using them adds dependency to your project, which can probably be avoided.

Recent versions of Qt recommend using QNetworkAccessManager to make network requests (including HTTP requests) and receive responses.

The easiest way to upload a file:

 QNetworkAccessManager *manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); manager->get(QNetworkRequest(QUrl("http://stackoverflow.com"))); 

When the replyFinished slot is replyFinished , the QNetworkReply object, which it accepts as a parameter, will contain the uploaded data, as well as metadata (headers, etc.).

A more complete example can be found in the Qt examples, you can read its source code here .

+6
source

Giuseppe is right, you do not need to use the libcurl, curlpp libraries and similar libraries. This is not necessary; Qt has a simple and working class.

Keep in mind that the standard way to send a request and receive a response is asynchronous. You always need to connect the processed manager (QNetworkReply *) to the slot.

If you send multiple requests and do not want to add a slot for each response, you can always start the event loop and connect the managers signal to the quit () slot of the event loop.

Something like that:

 QNetworkAccessManager *manager = new QNetworkAccessManager(this); QEventLoop *eventLoop = new QEventLoop(); QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), eventLoop, SLOT(quit()); manager->get(QNetworkRequest(QUrl("http://stackoverflow.com"))); eventLoop->exec(QEventLoop::ExcludeUserInputEvents); QByteArray replyData = reply->readAll(); ... //do what you want with the data your receive from reply 

Btw. I don’t know what you are doing. But if this is a mobile application, I would recommend you switch from VS to QtCreator IDE. It has a good simulator and a complete toolchain for testing mobile devices.

+5
source

All Articles