qt http通信请求demo (get post )其余类似
CNetwork()
{
manager = new QNetworkAccessManager(this);
}
void Get(const QString& url);
void Post(const QString& url_, const QByteArray &data_);
void handleGetReply();
void handlePostReply();
QNetworkAccessManager* manager;
头文件里面先来个get和post以及处理他们返回值的函数的函数声明和QNetworkAccessManager管理类的初始化
接下来看看具体函数实现
void CNetwork::Get(const QString& url_)
{
// 创建URL对象
QUrl reqUrl(url_);
// 发起GET请求
QNetworkReply* reply = manager->get(QNetworkRequest(reqUrl));
// 关联信号和槽,用于处理请求完成后的情况
connect(reply, &QNetworkReply::finished, this, &CNetwork::handleGetReply);
}
void CNetwork::Post(const QString& url_, const QByteArray &data_)
{
QUrl reqUrl(url_);
QNetworkRequest request(reqUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); // 设置Content-Type为JSO
QNetworkReply *reply = manager->post(request, data_);
// 关联信号和槽,用于处理请求完成后的情况
connect(reply, &QNetworkReply::finished, this, &CNetwork::handlePostReply);
}
void CNetwork::handleGetReply()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
// 获取响应的数据(这里假设获取文本内容)
obs = reply->readAll();
}
// 释放reply对象相关资源
reply->deleteLater();
}
}
void CNetwork::handlePostReply()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (reply)
{
if (reply->error() == QNetworkReply::NoError) {
// 获取响应的数据(这里假设获取文本内容)
QByteArray data = reply->readAll();
// 打印HTTP状态码
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << "HTTP Status Code: " << statusCode;
// 如果需要解析JSON数据,可以这样做
QJsonDocument jd = QJsonDocument::fromJson(data);
if (!jd.isNull())
{
handleJsonobject(jd.object());
}
reply->deleteLater();
}
else {
// 如果有错误,打印错误信息
qDebug() << "Error:" << reply->errorString();
}
// 释放reply对象相关资源
reply->deleteLater();
}
}
好了,已经完成了。