写了一个简单的显示天气信息的例子。
其中涉及到http, xml, c++11
天气信息是用webxml接口获取的,包括图片素材。
通过getSupportProvince获取支持的省份信息,getSupportCity获取当前省份中的城市,getWeatherbyCityName获取城市天气
由于QNetworkAccessManager的get请求是异步的所以我们需要在收到replyFinished应答后通知界面来显示信息,
以上三个接口都有一个回调函数作为参数,此回调函数就是用来显示界面信息的地方,使用到了c++11中的function和bind。
其中replyFinished涉及到了xml解析,部分格式如下所示,具体协议可以参考:webxml
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns="http://WebXml.com.cn/"><string>string</string><string>string</string>
</ArrayOfString>
1.获取所有的省份;
2.第一个省份为默认省份,获取当前省份的城市列表;
3.点击“查询”,获取城市天气信息后解析并显示在界面上;
4.为了保证当前的城市和天气信息一致,当城市改变后要清除之前的信息。
完整代码:https://github.com/tujiaw/weather/
部分代码如下:
citymanager.h
#ifndef CITYMANAGER_H
#define CITYMANAGER_H#include <QObject>
#include <functional>class QNetworkAccessManager;
class QNetworkReply;typedef std::function<void (const QStringList &strList)> OnMessage;class CityManager : public QObject
{Q_OBJECTpublic:CityManager(QObject *parent = 0);void getSupportProvince(const OnMessage &msg);void getSupportCity(const QString &provinceName, const OnMessage &msg);void getWeatherbyCityName(const QString &cityName, const OnMessage &msg);private slots:void replyFinished(QNetworkReply *);private:QNetworkAccessManager *net_;OnMessage onMessage_;
};#endif // CITYMANAGER_H
citymanager.cpp
#include "citymanager.h"#include <QtNetwork>
#include <QTextCodec>
#include <QXmlStreamReader>
#include <QWaitCondition>
#include <QMutex>
#include <QMutexLocker>// 获取天气信息接口:http://www.webxml.com.cn/zh_cn/weather_icon.aspx
CityManager::CityManager(QObject *parent): QObject(parent)
{net_ = new QNetworkAccessManager(this);QObject::connect(net_, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));}void CityManager::getSupportProvince(const OnMessage &msg)
{onMessage_ = msg;QUrl url("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportProvince?");QNetworkRequest request(url);net_->get(request);
}void CityManager::getSupportCity(const QString &provinceName, const OnMessage &msg)
{onMessage_ = msg;QString str("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName=");str.append(provinceName);QUrl url(str);QNetworkRequest request(url);net_->get(request);
}void CityManager::getWeatherbyCityName(const QString &cityName, const OnMessage &msg)
{onMessage_ = msg;QString str("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=");str.append(cityName);QUrl url(str);QNetworkRequest request(url);net_->get(request);
}void CityManager::replyFinished(QNetworkReply *reply)
{QTextCodec *codec = QTextCodec::codecForName("UTF-8");QString all = codec->toUnicode(reply->readAll());QStringList list;QXmlStreamReader reader(all);while (!reader.atEnd()) {reader.readNext();if (reader.isStartElement()) {if (reader.name() == "string") {list.append(reader.readElementText());}}}if (onMessage_) {onMessage_(list);}reply->deleteLater();
}