Qt5获取并解析中国天气网数据

网友投稿 419 2022-09-07

Qt5获取并解析中国天气网数据

天气查询 API 接口

中国天气网提供 3 个 API 接口,以北京为例:

3 个 Web API 即可返回对应城市的天气信息,返回的是 JSON 格式数据。(第一个访问不了 -’’-)

返回的 JSON 数据:

{ "weatherinfo": { "city":"北京", "cityid":"101010100", "temp":"27.9", "WD":"南风", "WS":"小于3级", "SD":"28%", "AP":"1002hPa", "njd":"暂无实况", "WSE":"<3", "time":"17:55", "sm":"2.1", "isRadar":"1", "Radar":"JC_RADAR_AZ9010_JB" }}

返回的 JSON 数据:

{ "weatherinfo": { "city":"北京", "cityid":"101010100", "temp1":"18℃", "temp2":"31℃", "weather":"多云转阴", "img1":"n1.gif", "img2":"d2.gif", "ptime":"18:00" }}

请求与响应

为方便起见,我们设置一个输入框获取城市代码,设置一个按钮触发查询请求,然后将实时气温显示在下面。

Show the code !

【头文件】

#ifndef#define#include #include #include #include namespace Ui {class MainWidget;}class MainWidget : public QWidget{ Q_OBJECTpublic: explicit MainWidget(QWidget *parent = 0); ~MainWidget();private slots: void slotReadyRead(); void downloadFinished(); void replyFinished(QNetworkReply *reply); void on_pushButton_clicked();private: Ui::MainWidget *ui; QNetworkAccessManager *manager; QNetworkReply *reply;};#endif// MAINWIDGET_H

【源文件】

#include "mainwidget.h"#include "ui_mainwidget.h"#include MainWidget::MainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MainWidget){ ui->setupUi(this); this->setWindowTitle(tr("天气查询")); manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));}MainWidget::~MainWidget(){ delete ui;}void MainWidget::on_pushButton_clicked(){ qDebug() << "clicked"; QNetworkRequest request; request.setUrl(QUrl(QString(" /* Set header */ request.setRawHeader(QByteArray("User-Agent"), QByteArray("Mozilla/5.0")); /* Auto redirect */ request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); reply = manager->get(request); connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); connect(reply, SIGNAL(finished()), this, SLOT(downloadFinished()));}void MainWidget::slotReadyRead(){ qDebug() << "ready";}void MainWidget::downloadFinished(){ qDebug() << "download"; reply->deleteLater();}void MainWidget::replyFinished(QNetworkReply *reply){ qDebug() << "reply"; /* Get status code */ QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if(statusCode.isValid()) { qDebug() << "status code:" << statusCode.toInt(); } QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute); if(reason.isValid()) { qDebug() << "reason:" << reason.toString(); } QNetworkReply::NetworkError err = reply->error(); if(err != QNetworkReply::NoError) { qDebug() << "Failed:" << reply->errorString(); } else { QByteArray bytes = reply->readAll(); QString string = QString::fromUtf8(bytes); qDebug() << string; }}

需要特别注意的是,由于请求发生重定向,所以一定要加上这行代码,设置自动跳转,否则会返回 302。

/* Auto redirect */request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);

解析 JSON 数据

创建函数 parseFromJson 用于读取、解析 JSON 数据,并在 TextBrowser 中直接显示出来。

void parseFromJson(const QString &jsonStr);

具体代码实现如下:

void MainWidget::parseFromJson(const QString &jsonStr){ QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(jsonStr.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qDebug() << "Parsed error"; return; } QJsonObject obj = doc.object(); if(obj.contains(QLatin1Literal("weatherinfo"))) { qDebug() << "Parsing"; QJsonObject subObj = obj.value("weatherinfo").toObject(); QString city = subObj["city"].toString(); QString temp = subObj["temp"].toString(); QString WD = subObj["WD"].toString(); QString WS = subObj["WS"].toString(); QString time = subObj["time"].toString(); ui->textBrowser->setText(QString("城市:%1\n气温:%2\n风向:%3\n风速:%4\n时间:%5").arg(city).arg(temp).arg(WD).arg(WS).arg(time)); }}

运行程序,输入城市代码,查询… 如下:

OK,你学会了吗?

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:从19岁到36岁,C罗争冠决心从未改变!
下一篇:ALSA 音频工具 amixer、aplay、arecord
相关文章

 发表评论

暂时没有评论,来抢沙发吧~