使用对象
1 QNetworkAccessManager--网络操作的管理者;
2 QNetworkRequest--网络请求的对象,用于接收url;
3 QNetworkReply--get或者post请求后的实体,实体会异步的进行数据的接收,需要手动销毁。
模块配置
QT += network
头文件
#include <QNetworkAccessManager>
#include <QNetworkReply>
函数实现
/**
* @brief receive_getReply
* @param reply
* 处理回答
*/
void receive_getReply(QNetworkReply *reply) {
if (nullptr == reply) {
qDebug() << "reply nullptr";
return;
}
/// 等待结束后再read
QObject::connect(reply, &QNetworkReply::finished, [reply]() {
/// read data
QByteArray byte = reply->readAll();
// reply->disconnect();
/// delete pointer
reply->deleteLater();
/// data to json
QJsonDocument jsonDocument = QJsonDocument::fromJson(byte.data());
/// process data
/// can emit in class::QObject
qDebug() << jsonDocument;
});
}
/**
* @brief request_get
* @param url
* 查询,get请求
* 注意,下方的QNetworkAccessManager 是静态对象
*/
void request_get(const QUrl &url) {
static QNetworkAccessManager manager;
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
receive_getReply(reply);
// QEventLoop loop;
/// [1]
// QObject::connect(&manager, &QNetworkAccessManager::finished, &loop, &QEventLoop::quit);
/// [2]
// QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
// loop.exec();
}
/**
* @brief test_network
* 测试fun
*/
void test_network() {
/// 天气预报查询api
/// 首尾不要用空格
QString url = R"(http://api.k780.com:88/?app=weather.future
&appkey=10003
&sign=b59bc3ef6191eb9f747dd4e83c99f2a4
&format=json
&weaid=苏州)";
request_get(QUrl(url));
}