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;
}
相关推荐
染指111025 分钟前
6.第二阶段x64游戏实战-分析人物状态
开发语言·汇编·windows·游戏·游戏逆向·x64dbg·x64游戏
forestsea1 小时前
Java虚拟机面试题:内存管理(中)
java·开发语言
longlong int1 小时前
【每日算法】Day 17-1:位图(Bitmap)——十亿级数据去重与快速检索的终极方案(C++实现)
开发语言·c++·算法
欧宸雅1 小时前
Perl语言的文件系统
开发语言·后端·golang
写代码的小王吧1 小时前
【安全】Java幂等性校验解决重复点击(6种实现方式)
java·linux·开发语言·安全·web安全·网络安全·音视频
淘源码d1 小时前
如何运用C#.NET快速开发一套掌上医院系统?
开发语言·c#·.net·源码·掌上医院
一个程序员(●—●)2 小时前
xLua环境控制+xLua的Lua调用C#的1
开发语言·unity·c#·lua
霍珵蕴2 小时前
Haskell语言的区块链安全
开发语言·后端·golang
vortex53 小时前
Bash中因数值比较引发的提权漏洞:数组注入与任意命令执行
linux·开发语言·安全·网络安全·渗透测试·bash
霍珵蕴3 小时前
R语言的嵌入式图形界面
开发语言·后端·golang