Qt实现Http请求

Qt中使用QNetworkAccessManager类来实现Http相关请求,本文介绍Http Get请求的简单实用方法。

下面是Qt中进行Http请求的简单步骤:

  • 定义QNetworkAccessManager指针及槽函数
  • 创建QNetworkAccessManager对象并关联槽函数
  • 在类的析构函数中删除QNetworkAccessManager对象
  • 实现槽函数
  • 调用Http请求

1、在头文件中定义QNetworkAccessManager指针及槽函数

private slots:
    void onNetworkReplyFinished(QNetworkReply *reply);

private:
QNetworkAccessManager *m_netAccessManager;

2、在构造函数中创建QNetworkAccessManager对象并关联信号槽

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_netAccessManager = new QNetworkAccessManager(this);

    //关联信号槽
    connect(m_netAccessManager, &QNetworkAccessManager::finished, this, &MainWindow::onNetworkReplyFinished);
}

3、在析构函数中删除QNetworkAccessManager对象

MainWindow::~MainWindow()
{
    delete ui;
    delete m_netAccessManager;
}

4、实现槽函数

void MainWindow::onNetworkReplyFinished(QNetworkReply *reply)
{
    //状态码:200表示请求成功
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    qDebug() << "operation: " << reply->operation(); //请求方式
    qDebug() << "status code: " << statusCode; //状态码
    qDebug() << "url: " << reply->url(); //url
    qDebug() << "raw header: " << reply->rawHeaderList(); //header

    if (statusCode != 200 || reply->error() != QNetworkReply::NoError)
    {
        qDebug() << "请求数据失败:" << reply->errorString().toLocal8Bit().data(); //error
        return;
    }

    //获取响应信息
    QByteArray replyData = reply->readAll();
    auto byteArray = QString(replyData).toLocal8Bit();

    qDebug() << "read all: " << byteArray.data();

    //释放内存
    reply->deleteLater();
}

5、调用Get方法

QUrl url("the url");
m_netAccessManager->get(QNetworkRequest(url));
posted @ 2024-11-07 23:06  xhubobo  阅读(35)  评论(0编辑  收藏  举报