1.首先在项目配置里面添加network,qmake项目如下,CMake项目类似
QT += network
2.使用头文件
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument> //处理json字符串
3.定义私有私有类型全局变量
private:
QNetworkAccessManager *nam;
4.网络请求模块初始化
nam=new QNetworkAccessManager(this);
5.发出get请求
QString url="www.baidu.com" //替换成实际的网页
QNetworkRequest request;
request.setUrl(url);
QNetworkReply *reply=nam->get(request);
//处理相应请求
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
if (reply->error() == QNetworkReply::NoError) {
// qDebug() << "Request successful!";
QString reply_data = reply->readAll();
})
6.发出post请求
QJsonObject json;
json.insert("User", "admin");
json.insert("Password", "admin");
QJsonDocument document;
document.setObject(json);
QByteArray dataArray = document.toJson(QJsonDocument::Compact);
QString url="www.baidu.com" //替换成实际的网页
QNetworkRequest request;
request.setUrl(url);
nam->post(request,dataArray);