1. 添加网络模块
如果要使用http获取数据,需要在.pro文件中,添加网路模块:
QT += core gui network //补充network
2. 申明网络对象 + 槽函数
在mainwindow.h 中添加http通信的QNetworkAccessManager指针对象,用于处理Http 返回数据onReplied 槽函数
#include <QNetworkAccessMenager>
#include <QNetworkReply>
//在mainwindow.h里加入
private:
QNetworkAccessManager* mNetAccessManager;
private slots:
void onReplied(QNetworkReply* reply);
//在mainwindow.cpp里
mNetAccessManager = new QNetworkAccessManager(this);
//qt中进行http请求的开端
connect(mNetAccessManager, &QNetworkAccessManager::finished, this, onReplied);//finished信号
//连接信号和slot
3.发送http请求
protected:
void getWeatherInfo(QString cityCode);
//在构造中请求天气预报:connect(,finished,this) 后面 mainwindow.cpp
getWeatherInfo("101010100");//101010100 是北京的天气编码
void getWeatherInfo(QString CityCode){
QUrl url("http://t.weather.itboy.net/api/weather/city/" + cityCode);
mNetAccessManager->get(QNetworkRequest(url));
}
4. 接受服务端请求
内容全部在Reply里,学习如何使用reply的各种函数从中获得数据是很重要的学习。
void MainWindow::onReplied(QNetworkReply* reply){
//所有内容都储存在reply里面
//响应码 200, 表示请求成功;404,表示not found
int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << "operation: " << reply->operation(); //请求方式
qDebug() << "status code: " << status_code;
qDebug() << "url: " << reply->url();
qDebug() << "raw header: " <<reply->rawHeaderList();
//以上可要可不要,仅做学习功能处理
if( reply->error() != QNetworkReply::NoError || status_code != 200){//俩个方法取其一即可
QMessageBox::warning(this, "天气", "请求数据失败!", QMessageBox::ok);
}else {
//获取响应信息
QByteArray reply_data = reply->readAll();
qDebug() << "read all: " << byteArray.data();
//parseJson()
}
reply->deleteLater();//把数据删除,防止内存过度占用
}
这一章实话实说有点没懂,要多做多看多思考,最好做出自己的创意作品