The QNetworkAccessManager class in Qt handles network communication, including HTTP operations. The following steps demonstrate how to perform a basic HTTP GET request.
Step 1: Declare Members in the Header
Define the network menager instance and the slot to handle encoming responses.
private slots:
void handleResponse(QNetworkReply *networkReply);
private:
QNetworkAccessManager *httpClient;
Step 2: Initialize and Connect Signals
In the class constructor, instantiate the manager and connect the finished signal to the custom slot.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
httpClient = new QNetworkAccessManager(this);
// Bind the signal to the slot
connect(httpClient, &QNetworkAccessManager::finished,
this, &MainWindow::handleResponse);
}
Step 3: Cleanup Resources
Ensure the manager is properly deallocated in the destructor.
MainWindow::~MainWindow()
{
delete ui;
delete httpClient;
}
Step 4: Implement the Resposne Handler
Process the reply, check for errors, read the payload, and schedule the reply object for deletion.
void MainWindow::handleResponse(QNetworkReply *networkReply)
{
// Extract the HTTP status code
int httpStatus = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << "Method:" << networkReply->operation();
qDebug() << "Status:" << httpStatus;
qDebug() << "Target URL:" << networkReply->url();
qDebug() << "Headers:" << networkReply->rawHeaderList();
if (httpStatus != 200 || networkReply->error() != QNetworkReply::NoError)
{
qDebug() << "Request failed:" << networkReply->errorString();
networkReply->deleteLater();
return;
}
// Read the response body
QByteArray payload = networkReply->readAll();
qDebug() << "Response Data:" << QString::fromUtf8(payload);
// Free memory
networkReply->deleteLater();
}
Step 5: Execute the GET Request
Create a request using a QUrl and pass it to the manager's get method.
QUrl targetUrl("https://api.example.com/data");
httpClient->get(QNetworkRequest(targetUrl));