Simple HTTP request in QNetworkAccessManager doesn't work
-
I'm trying to implement simple HTTP request with QNetworkAccessManager, but it does nothing. Code compiles and runs fine, but my method connected to
&QNetworkAccessManager::finished
seems to be never called. Connect itself returns true.I have this code:
main.cpp
#include <iostream> #include <QApplication> #include "main.h" MyObject::MyObject(QObject* parent) { manager = new QNetworkAccessManager(parent); } void MyObject::TestConnection() { auto status = connect(manager, &QNetworkAccessManager::finished, this, &MyObject::ReplyFinished); qDebug() << "Connection status:" << status; manager->get(QNetworkRequest(QUrl("https://google.com"))); } void MyObject::ReplyFinished(QNetworkReply *reply) { QString answer = reply->readAll(); qDebug() << answer; } int main(int argc, char *argv[]) { auto *app = new QApplication(argc, argv); auto myObject = new MyObject(app); myObject->TestConnection(); return 0; }
main.h
#include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> class MyObject : public QObject { Q_OBJECT public: MyObject(QObject* parent); void TestConnection(); void ReplyFinished(QNetworkReply *reply); QNetworkAccessManager *manager; };
Is there something wrong? I walked through a bunch of forums and guides and tried multiple ways to get this working:
- connected SIGNALS and SLOTS
- binded finished(), readyRead() on reply object
- used lambda expression instead of method reference
- tried HTTP and HTTPS with different domains
I'm building this in CLion on Linux with CMake, can it be related? Maybe this code will work for you and there is a problem with my platform.
CMakeLists.txt
cmake_minimum_required(VERSION 3.17) project(http) set(CMAKE_CXX_STANDARD 20) set(CMAKE_AUTOMOC ON) add_executable(http main.cpp main.h) find_package(Qt5Widgets REQUIRED) find_package(Qt5Network REQUIRED) target_link_libraries(${PROJECT_NAME} Qt5::Widgets Qt5::Network)
Thank you in advance.
-
I found out what is wrong. I forgot to execute an application object. The program finishes faster then the response can actually arrive.
Replacing
return 0;
withreturn app->exec();
inmain()
did the trick.Can I somehow wait for the response and then exit a program?