Qt 使用HTTP请求网络API并接收返回的JSON格式的数据

引入网络模块:

cpp 复制代码
QT  += core gui network

mainwindow.h:

cpp 复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMessageBox>

#include <QNetworkAccessManager>
#include <QNetworkReply>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    // 请求天气数据成功后自动调用 onReply() 槽函数
    void onReply(QNetworkReply* reply);
protected:
    // 根据城市编码获取城市天气信息
    void getWeatherInfo(QString cityCode);
private:
    Ui::MainWindow *ui;
    // 发送网络请求 和 处理网络响应
    QNetworkAccessManager *m_networkAccessManager;
};
#endif // MAINWINDOW_H

mainwindow.cpp:

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    m_networkAccessManager = new QNetworkAccessManager(this);
    // 获取天气数据完成后自动触发系统信号 finished,调用自定义槽函数 onReply
    connect(m_networkAccessManager,&QNetworkAccessManager::finished,this,&MainWindow::onReply);
    
    // 根据城市编码获取城市天气信息
    // 101010100为北京市天气编码
    getWeatherInfo("101010100");
}

MainWindow::~MainWindow()
{
    delete ui;
}
// 请求数据成功后自动调用 onReply() 槽函数
void MainWindow::onReply(QNetworkReply *reply)
{
    // 状态码:响应成功为 200
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    //    qDebug()<<"请求方式:"<<reply->operation();
    //    qDebug()<<"状态码:"<<statusCode;
    //    qDebug()<<"URL:"<<reply->url();
    //    qDebug()<<"响应头:"<<reply->rawHeaderList();
    if(reply->error() != QNetworkReply::NoError || statusCode != 200)
    {// 天气数据请求失败
        QMessageBox::warning(this,"天气","天气数据请求失败",QMessageBox::Ok);
    }
    else
    {// 天气数据请求成功
        QByteArray byteArray = reply->readAll();
        qDebug()<<" info::::::"<<byteArray.data();
    }
    // 必须释放内存,否则会造成内存泄露
    reply->deleteLater();
}
// 根据城市编码获取城市天气信息
void MainWindow::getWeatherInfo(QString cityCode)
{
    QUrl url("http://t.weather.itboy.net/api/weather/city/"+cityCode);
    // 使用 get 请求方式
    m_networkAccessManager->get(QNetworkRequest(url));
}
相关推荐
IOT-Power7 小时前
QT TCP 源码结构框架
qt
Java Fans7 小时前
Qt Designer 和 PyQt 开发教程
开发语言·qt·pyqt
开始了码7 小时前
深入理解回调函数:从概念到 Qt 实战
开发语言·qt
Irene199110 小时前
Prettier 配置文件 .prettierrc.js 和 .prettierrc.json 的区别
javascript·json
gxh199212 小时前
4步将HTTP请求升级为HTTPS
运维·服务器·网络协议·http·https
世转神风-13 小时前
qt-pro文件名词解释
开发语言·qt
kupeThinkPoem14 小时前
Qt中addSpacing参数为0的作用
qt
꧁坚持很酷꧂15 小时前
QCustomPlot绘制曲线
qt
23G15 小时前
Fastjson转换jsonStr时设置SerializerFeature.DisableCircularReferenceDetect不生效
json
函数的彼端16 小时前
iOS Model Generator - 让 JSON 转模型变得简单高效
ios·json·cocoa