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;
}
相关推荐
克鲁德战士1 分钟前
【Java并发编程的艺术3】Java内存模型(下)
java·开发语言·redis
xianwu5431 分钟前
MySQL索引原理
linux·开发语言·网络·c++·git
搬砖的小码农_Sky5 分钟前
C语言:树
c语言·开发语言·数据结构
是小博同学鸭13 分钟前
【面向对象的程序设计——集合框架】主要接口
java·开发语言
qq7621182236 分钟前
arm Rk1126 编译Qt工程报错: Could not find qmake spec
arm开发·qt
赛丽曼1 小时前
Python中的深浅拷贝
开发语言·python
Object~1 小时前
【第十课】Rust并发编程(一)
开发语言·后端·rust
techdashen2 小时前
Go与黑客(第一部分)
开发语言·后端·golang
earthzhang20212 小时前
《深入浅出HTTPS》读书笔记(9):对称加密算法
开发语言·前端·网络协议·https·1024程序员节