QT使用Http协议通信

介绍

使用QT进行应用开发时,有时候需要进行客户端和服务端的网络通信,网络通信常用的一种协议就是http协议。QT对http协议进行了封装,下面将介绍两种http通信方式的使用。

在使用http时需要在pro文件中添加对应的模块。

cpp 复制代码
QT += network

http主要两种通信方式为get和post两种

1.多个独立参数GET请求
cpp 复制代码
int NormalGetRequest(QString paramer1, QString paramer2)
{
    //生成对应的网络请求
    QNetworkRequest request;
    QString scheme = "http";
    QString serverAddr = "192.168.0.1";
    QString port = "80";
    QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
    QString fullRequest = requestHeader + QString("/api/vi/user/getrequest?paramer1=%1&paramer2=%2").arg(paramer1).arg(paramer2);
    request.setUrl(QUrl(fullRequest));
 
    //发送Get请求
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.get(request);
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
 
    //对请求的返回异常进行处理
    if(reply->error() != QNetworkReply::NoError)
    {
        return reply->error();
    }
 
    //解析返回的Json结果
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }
    QJsonObject rootObj = jsonDoc.object();
    QString codeStr = rootObj.value("code").toString();
    if (codeStr.compare("200") == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("result"))
        {
 
        }
        return 0;
    }
    else
    {
        //请求失败对对应的处理
        return codeStr.toInt();
    }
}
2.参数数组GET请求
cpp 复制代码
int GetRequestWithArray(QVector<QString> m_filePathVector)
{ 
    QJsonArray array;
    for(int index=0; index<m_filePathVector.size(); ++index)
    {
        QJsonObject object;
        object.insert("index",QString::number(index));
        object.insert("path",m_filePathVector.at(index));
        array.append(object);
    }
 
    QJsonDocument document;
    document.setArray(array);
    QString arrayString = document.toJson(QJsonDocument::Compact);
 
    //生成对应的网络请求
    QNetworkRequest request;
    QString scheme = "http";
    QString serverAddr = "192.168.0.1";
    QString port = "80";
    QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
    QString fullRequest = requestHeader + QString("/api/vi/user/getarray?paramers=%1").arg(arrayString);
    request.setUrl(QUrl(fullRequest));
 
    //获取错误
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.get(request);
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    if(reply->error() != QNetworkReply::NoError)
    {
        return reply->error();
    }
 
    //解析返回的Json结果
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }
    QJsonObject rootObj = jsonDoc.object();
    QString codeStr = rootObj.value("code").toString();
    if (codeStr.compare("200") == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("result"))
        {
 
        }
        return 0;
    }
    else
    {
        //请求失败对对应的处理
        return codeStr.toInt();
    }
}
3.上传参数数据POST请求
cpp 复制代码
int NormalPostRequest(QString paramer1, QString paramer2)
{
    //生成对应的网址请求
    QNetworkRequest request;
    QString scheme = "http";
    QString serverAddr = "192.168.0.1";
    QString port = "80";
    QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
    QString fullRequest = requestHeader + "/api/v1/user/postrequest";
    request.setUrl(QUrl(fullRequest));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
 
    //获取对应的参数数据
    QByteArray data;
    data.append("paramer1=");
    data.append(paramer1.toUtf8());
    data.append("&paramer2=");
    data.append(paramer2.toUtf8());
 
    //发送请求
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.post(request,data);
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    if(reply->error() != QNetworkReply::NoError)
    {
        return reply->error();
    }
 
 
    //解析返回的Json结果
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }
    QJsonObject rootObj = jsonDoc.object();
    QString codeStr = rootObj.value("code").toString();
    if (codeStr.compare("200") == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("result"))
        {
 
        }
        return 0;
    }
    else
    {
        //请求失败对对应的处理
        return codeStr.toInt();
    }
}
4.上传参数和文件POST请求
cpp 复制代码
int PostRequestWithFile(QString paramer1, QString paramer2,QString filePath)
{
 
    //生成对应的网址请求
    QFileInfo fileInfo(filePath);
    QString fileName =fileInfo.fileName();
 
    QFile* inputFile = new QFile(filePath);
    inputFile->open(QIODevice::ReadOnly);
 
    //multipart请求
    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    //文件块
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                                 QVariant(QString("form-data; name=\"uploadfile\";filename=\"%1\"").arg(fileName)));
    filePart.setBodyDevice(inputFile);
    inputFile->setParent(multiPart);
    multiPart->append(filePart);
 
    QHttpPart paramer1Part;
    paramer1Part.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"paramer1\""));
    paramer1Part.setBody(paramer1.toUtf8());
    multiPart->append(paramer1Part);
 
    QHttpPart paramer2Part;
    paramer2Part.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"paramer2\""));
    paramer2Part.setBody(paramer2.toUtf8());
    multiPart->append(paramer2Part);
 
 
    //生成对应的网址请求
    QNetworkRequest request;
    QString scheme = "http";
    QString serverAddr = "192.168.0.1";
    QString port = "80";
    QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
    QString fullRequest = requestHeader + "/api/v1/user/postrequestwithfile";
    request.setUrl(QUrl(fullRequest));
 
    //发送请求
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.post(request,multiPart);
    multiPart->setParent(reply);
 
    QEventLoop eventLoop;
    QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)),&eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
 
    if(reply->error() != QNetworkReply::NoError)
    {
        return reply->error();
    }
 
    //解析返回的Json结果
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }
    QJsonObject rootObj = jsonDoc.object();
    QString codeStr = rootObj.value("code").toString();
    if (codeStr.compare("200") == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("result"))
        {
 
        }
        return 0;
    }
    else
    {
        //请求失败对对应的处理
        return codeStr.toInt();
    }
}
5.下载文件GET请求
cpp 复制代码
int DownloadFileFromWeb(QString fileUrl,QString&fileSavePath)
{
    QNetworkRequest request;
    QUrl url(fileUrl);
    QFileInfo fileInfo(url.path());
    QString fileName = fileInfo.fileName();
    QNetworkAccessManager *accessManager=new QNetworkAccessManager();
    request.setUrl(url);
    QNetworkReply *reply  = accessManager->get(request);
    QEventLoop loop;
    QObject::connect(accessManager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
//如果需要下载进度需要关联对应的信号
//connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(LoadProgress(qint64, qint64)));
    loop.exec(QEventLoop::ExcludeUserInputEvents);
 
    //获取下载返回值
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if (statusCode.toInt() != 200)
    {
        return -1;
    }
 
    //保存下载的文件
    QFile file(fileSavePath);
    if(!file.open(QIODevice::WriteOnly))
    {
        return -2;
    }
    file.write(reply->readAll());
    file.close();
    return 0;
}
相关推荐
上海_彭彭21 分钟前
【提效工具开发】Python功能模块执行和 SQL 执行 需求整理
开发语言·python·sql·测试工具·element
3345543229 分钟前
element动态表头合并表格
开发语言·javascript·ecmascript
沈询-阿里33 分钟前
java-智能识别车牌号_基于spring ai和开源国产大模型_qwen vl
java·开发语言
残月只会敲键盘1 小时前
面相小白的php反序列化漏洞原理剖析
开发语言·php
ac-er88881 小时前
PHP弱类型安全问题
开发语言·安全·php
ac-er88881 小时前
PHP网络爬虫常见的反爬策略
开发语言·爬虫·php
爱吃喵的鲤鱼1 小时前
linux进程的状态之环境变量
linux·运维·服务器·开发语言·c++
DARLING Zero two♡1 小时前
关于我、重生到500年前凭借C语言改变世界科技vlog.16——万字详解指针概念及技巧
c语言·开发语言·科技
7年老菜鸡1 小时前
策略模式(C++)三分钟读懂
c++·qt·策略模式
Gu Gu Study1 小时前
【用Java学习数据结构系列】泛型上界与通配符上界
java·开发语言