文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Qt怎么用QNetwork实现上传数据

2023-07-05 06:28

关注

这篇文章主要介绍了Qt怎么用QNetwork实现上传数据的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Qt怎么用QNetwork实现上传数据文章都会有所收获,下面我们一起来看看吧。

1、利用Qt提供的类实现向服务器发送post和get请求

#include <QCoreApplication>#include <QNetworkAccessManager>#include <QNetworkRequest>#include <QNetworkReply>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>#include <QJsonParseError>#include <QJsonValue>#include <QString>#include <QDebug>#include <QFile>#include <QDateTime>#include <QDir>#include <QThread>#pragma execution_character_set("utf-8")void sendPostRequest(){    QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();    //设置url    QString url = "http://localhost:80/post";    //设置头信息    QNetworkRequest requestInfo;    requestInfo.setUrl(QUrl(url));    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));    //requestInfo.setRawHeader("Content-Type","application/json");//服务器要求的数据头部    //requestInfo.setRawHeader("Accept","text/json,*, const QString& strExContentDisposition )    {        m_pData = nullptr;        m_nDataLen = 0;        m_sName = strName;        m_sValue = strValue;        m_sContentType = strContentType;        m_sExContentDisposition = strExContentDisposition;    }    CMultiPartItem::CMultiPartItem(const QString& strName, void* pData, int nLen,        const QString& strContentType , const QString& strExContentDisposition )    {        m_pData = pData;        m_nDataLen = nLen;        m_sName = strName;        m_sContentType = strContentType;        m_sExContentDisposition = strExContentDisposition;    }    //    bool HttpGet(        const HttpRequestData& data,        QByteArray& respData,        int nTimeoutmsec ,        QString& errMsg,        int* pStatuCode )    {        // Assemble Url        QString strUrl = data.strUrl;        if (!data.strServer.isEmpty())            strUrl = data.strServer + ":" + QString::number(data.nPort) + "/" + data.strUrl;        const QUrl url = QUrl::fromUserInput(strUrl);        // Send Get Requeset        QNetworkRequest request(url);        for (auto iter = data.mapHeaders.begin(); iter != data.mapHeaders.end(); iter++)        {            request.setHeader(iter->first, iter->second);        }        QNetworkAccessManager qNetAccessManager;        QNetworkReply* reply = qNetAccessManager.get(request);        if (reply == nullptr)            return false;        // Set time out        QTimer timer;        timer.setInterval(nTimeoutmsec);    // 设置超时时间 30 秒        timer.setSingleShot(true);          // 单次触发        // Set Loop Event        QEventLoop eventLoop;        QObject::connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);        QObject::connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);        timer.start();        int eRes = eventLoop.exec(QEventLoop::ExcludeUserInputEvents);        bool bResult = false;        if (timer.isActive())        {            timer.stop();            QNetworkReply::NetworkError replyError = reply->error();            QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);            int nStatusCode = variant.toInt();            if (nullptr != pStatuCode)            {                *pStatuCode = nStatusCode;            }            if (replyError != QNetworkReply::NoError)            {                errMsg = reply->errorString();                qDebug() << "Error String : " << errMsg << "\n";            }            else            {                if (nStatusCode == 200)                {                    // Accept Response                    respData = reply->readAll();                    bResult = true;                }                else                {                    bResult = false;                }            }        }        else        {            QObject::disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);            reply->abort();            qDebug() << strUrl << ":Timeout\n";        }        reply->deleteLater();        reply = nullptr;        return bResult;    }    bool HttpPost(const HttpRequestData &data, QByteArray &respData, QString &errMsg, int nTimeoutmsec)    {        // Assemble Url        QString strUrl = data.strUrl;        if (!data.strServer.isEmpty())            strUrl = data.strServer + ":" + QString::number(data.nPort) + "/" + data.strUrl;        const QUrl url = QUrl::fromUserInput(strUrl);        // Send Post Requeset        QNetworkRequest request(url);        for (auto iter = data.mapHeaders.begin(); iter != data.mapHeaders.end(); iter++)        {            request.setHeader(iter->first, iter->second);        }        QNetworkAccessManager qNetAccessManager;        QNetworkReply* reply = qNetAccessManager.post(request, data.bytePostData);        if (reply == nullptr)            return false;        // Set time out        QTimer timer;        timer.setInterval(nTimeoutmsec);    // 设置超时时间 30 秒        timer.setSingleShot(true);          // 单次触发        // Set Loop Event        QEventLoop eventLoop;        QObject::connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);        QObject::connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);        timer.start();        eventLoop.exec(QEventLoop::ExcludeUserInputEvents);        bool bResult = false;        if (timer.isActive())        {            timer.stop();            QNetworkReply::NetworkError replyError = reply->error();            if (replyError != QNetworkReply::NoError)            {                errMsg = reply->errorString();                qDebug() << "Error String : " << reply->errorString() << "\n";            }            else            {                QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);                int nStatusCode = variant.toInt();                if (nStatusCode == 200)                {                    // Accept Response                    respData = reply->readAll();                    bResult = true;                }            }        }        else        {            QObject::disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);            reply->abort();            errMsg = (strUrl + ":Timeout\n");            qDebug() << strUrl << ":Timeout\n";        }        reply->deleteLater();        reply = nullptr;        return bResult;    }    bool UploadMultipartData(const HttpRequestData &data, const CMultiPartDatas &multiPartDatas, QByteArray &respData, QString &errMsg, int nTimeoutmsec)    {        QString strUrl = data.strUrl;        if (!data.strServer.isEmpty())            strUrl = data.strServer + ":" + QString::number(data.nPort) + "/" + data.strUrl;        const QUrl url = QUrl::fromUserInput(strUrl);        // 创建网络请求        QNetworkRequest request;        request.setUrl(url);        QHttpMultiPart httpMultiPart(QHttpMultiPart::FormDataType);        // 解决Qt自动解析MultiPart得到boundary=带双引号问题        for (auto iter = data.mapHeaders.begin(); iter != data.mapHeaders.end(); iter++)        {            request.setHeader(iter->first, iter->second);        }        request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data;boundary=" + httpMultiPart.boundary());        FOR_EACH(itemPart, multiPartDatas)        {            QHttpPart httpPart;            {                QString strContentDisposition = QString("form-data; name=\"%1\"%2").arg(itemPart.m_sName)                    .arg(itemPart.m_sExContentDisposition.isEmpty() ? "" : "; " + itemPart.m_sExContentDisposition);                httpPart.setHeader(QNetworkRequest::ContentDispositionHeader, strContentDisposition.toUtf8());                if (itemPart.m_sContentType.isEmpty() == false)                {                    httpPart.setHeader(QNetworkRequest::ContentTypeHeader, itemPart.m_sContentType.toUtf8());                }                if (itemPart.m_pData)                {                    httpPart.setBody(QByteArray((const char*)itemPart.m_pData, itemPart.m_nDataLen));                }                else                {                    httpPart.setBody(itemPart.m_sValue.toUtf8());                }            }            httpMultiPart.append(httpPart);        }        QNetworkAccessManager qNetAccessManager;        QNetworkReply* reply = qNetAccessManager.post(request, &httpMultiPart);        if (reply == nullptr)        {            errMsg = QObject::tr("发送失败");            return false;        }        QList<QByteArray> headers = reply->rawHeaderList();        // Set time out        QTimer timer;        timer.setInterval(nTimeoutmsec);    // 设置超时时间 30 秒        timer.setSingleShot(true);          // 单次触发        // Set Loop Event        QEventLoop eventLoop;        QObject::connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);        QObject::connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);        timer.start();        eventLoop.exec(QEventLoop::ExcludeUserInputEvents);        bool bResult = false;        if (timer.isActive())        {            timer.stop();            QNetworkReply::NetworkError replyError = reply->error();            if (replyError != QNetworkReply::NoError)            {                errMsg = reply->errorString();                qDebug() << "Error String : " << reply->errorString() << "\n";            }            else            {                QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);                int nStatusCode = variant.toInt();                if (nStatusCode == 200)                {                    // Accept Response                    respData = reply->readAll();                    bResult = true;                }            }        }        else        {            QObject::disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);            reply->abort();            qDebug() << data.strUrl << ":Timeout\n";        }        reply->deleteLater();        reply = nullptr;        return bResult;    }    bool UploadMultipartData(const QString &strURL, const CMultiPartDatas &multiPartDatas, QByteArray &respData, QString &errMsg, int nTimeoutmsec)    {        // 创建网络请求        QNetworkRequest request;        request.setUrl(QUrl::fromUserInput(strURL));        QHttpMultiPart httpMultiPart(QHttpMultiPart::FormDataType);        // 解决Qt自动解析MultiPart得到boundary=带双引号问题        request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data;boundary=" + httpMultiPart.boundary());        foreach (itemPart, multiPartDatas)        {            QHttpPart httpPart;            {                QString strContentDisposition = QString("form-data; name=\"%1\"%2").arg(itemPart.m_sName)                    .arg(itemPart.m_sExContentDisposition.isEmpty() ? "" : "; " + itemPart.m_sExContentDisposition);                httpPart.setHeader(QNetworkRequest::ContentDispositionHeader, strContentDisposition.toUtf8());                if (itemPart.m_sContentType.isEmpty() == false)                {                    httpPart.setHeader(QNetworkRequest::ContentTypeHeader, itemPart.m_sContentType.toUtf8());                }                if (itemPart.m_pData)                {                    httpPart.setBody(QByteArray((const char*)itemPart.m_pData, itemPart.m_nDataLen));                }                else                {                    httpPart.setBody(itemPart.m_sValue.toUtf8());                }            }            httpMultiPart.append(httpPart);        }        QNetworkAccessManager qNetAccessManager;        QNetworkReply* reply = qNetAccessManager.post(request, &httpMultiPart);        if (reply == nullptr)        {            errMsg = QObject::tr("发送失败");            return false;        }        QList<QByteArray> headers = reply->rawHeaderList();        // Set time out        QTimer timer;        timer.setInterval(nTimeoutmsec);    // 设置超时时间 30 秒        timer.setSingleShot(true);          // 单次触发        // Set Loop Event        QEventLoop eventLoop;        QObject::connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);        QObject::connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);        timer.start();        eventLoop.exec(QEventLoop::ExcludeUserInputEvents);        bool bResult = false;        if (timer.isActive())        {            timer.stop();            QNetworkReply::NetworkError replyError = reply->error();            if (replyError != QNetworkReply::NoError)            {                errMsg = reply->errorString();                qDebug() << "Error String : " << reply->errorString() << "\n";            }            else            {                QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);                int nStatusCode = variant.toInt();                if (nStatusCode == 200)                {                    // Accept Response                    respData = reply->readAll();                    bResult = true;                }            }        }        else        {            QObject::disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);            reply->abort();            qDebug() << strURL << ":Timeout\n";        }        reply->deleteLater();        reply = nullptr;        return bResult;    }}

关于“Qt怎么用QNetwork实现上传数据”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Qt怎么用QNetwork实现上传数据”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网行业资讯频道。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯