主要包含:
1.qt网络类和qjson类对象的使用
2.免费的天气api网址
3.全国大部分城市天气代码,使用第二种方式用到城市天气代码
- #weatherforecast.h 文件内容
-
-
- #ifndef WEATHERFORECAST_H
- #define WEATHERFORECAST_H
-
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- namespace Ui {
- class weatherforecast;
- }
-
- class weatherforecast : public QWidget
- {
- Q_OBJECT
-
- public:
- explicit weatherforecast(QWidget *parent = nullptr);
- ~weatherforecast();
-
- private:
- Ui::weatherforecast *ui;
- QNetworkAccessManager*manger; //
- QNetworkRequest request;
- QByteArray all;
-
- };
-
- #endif // WEATHERFORECAST_H
-
-
- #weatherforecast.cpp 文件内容
-
-
- #include "weatherforecast.h"
- #include "ui_weatherforecast.h"
-
- weatherforecast::weatherforecast(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::weatherforecast)
- {
- ui->setupUi(this);
- manger=new QNetworkAccessManager(this);
- connect(manger,&QNetworkAccessManager::finished,[this](QNetworkReply * reply){
-
- all = reply->readAll();
- QString arr_str(all);
- qDebug()<
- QJsonParseError error;
- QJsonDocument jsonDoc=QJsonDocument::fromJson(arr_str.toUtf8(),&error);
- if(error.error != QJsonParseError::NoError)
- {
-
- }
-
- QJsonObject jsonobject=jsonDoc.object();
- if(jsonobject.contains("data")) // 是否包含data
- {
- QJsonValue data_value=jsonobject.value("data");
- if(data_value.isObject())
- {
- QJsonObject object_data =data_value.toObject();
- QJsonValue yesterday_value=object_data.value("yesterday");
- if(yesterday_value.isObject())
- {
- QJsonObject yesterday_data =yesterday_value.toObject();
- qDebug()<< yesterday_data.value("date").toString();
- qDebug()<< yesterday_data.value("high").toString();
- qDebug()<< yesterday_data.value("fx").toString();
- qDebug()<< yesterday_data.value("low").toString();
- }
- }
- }
-
- });
-
- //天气接口api1 城市名称获取天气信息
- // QString str1("http://wthrcdn.etouch.cn/weather_mini?city=深圳");
- //this->manger->get(QNetworkRequest(QUrl(str1)));
-
- //天气接口api2 城市代码获取天气信息
- //全国大部分城市天气代码网址:https://www.cnblogs.com/emo-Studio/p/6840534.html
- QString str2("http://t.weather.sojson.com/api/weather/city/CHXX0116");
- this->manger->get(QNetworkRequest(QUrl(str2)));
-
- }
-
- weatherforecast::~weatherforecast()
- {
- delete ui;
- }
-
-
-
-