您好,登錄后才能下訂單哦!
這篇文章主要介紹了Qt怎么用QNetwork實現上傳數據的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Qt怎么用QNetwork實現上傳數據文章都會有所收獲,下面我們一起來看看吧。
#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,*/*;q=0.5");//服務器要求的數據頭部 //發送數據 QJsonObject regionObject; regionObject.insert("name","333"); regionObject.insert("height", "2"); regionObject.insert("dir", "0"); QJsonArray pointAry; pointAry.append(0.8); pointAry.append(1.0); pointAry.append(0.0); pointAry.append(1.8); pointAry.append(2.0); pointAry.append(0.0); regionObject.insert("points", QJsonValue(pointAry)); QJsonObject jsonObject; jsonObject.insert("Code", "asss"); jsonObject.insert("parentId", 0); jsonObject.insert("depot", "past"); jsonObject.insert("region", QJsonValue(regionObject)); QJsonDocument jsonDoc; jsonDoc.setObject(jsonObject); QByteArray qByteHttpData = jsonDoc.toJson(); QNetworkReply *reply = m_pHttpMgr->post(requestInfo, qByteHttpData); //添加事件循環機制,返回后再運行后面的 QEventLoop eventLoop; QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit())); eventLoop.exec(); //block until finish //錯誤處理 if (reply->error() != QNetworkReply::NoError) { qDebug()<<"request protobufHttp handle errors here"; QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); //statusCodeV是HTTP服務器的相應碼,reply->error()是Qt定義的錯誤碼,可以參考QT的文檔 qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error()); qDebug(qPrintable(reply->errorString())); } //請求收到的結果 QByteArray responseByte = reply->readAll(); QString strRes = responseByte; qDebug() << "Post:" << strRes; } void sendGetRequest() { QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager(); //設置url QString url = "http://localhost:80/Get; QNetworkRequest requestInfo; requestInfo.setUrl(QUrl(url)); //添加事件循環機制,返回后再運行后面的 QEventLoop eventLoop; QNetworkReply *reply = m_pHttpMgr->get(requestInfo); QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit())); eventLoop.exec(); //block until finish //錯誤處理 if (reply->error() != QNetworkReply::NoError) { qDebug()<<"request protobufHttp handle errors here"; QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); //statusCodeV是HTTP服務器的相應碼,reply->error()是Qt定義的錯誤碼,可以參考QT的文檔 qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error()); qDebug(qPrintable(reply->errorString())); } //請求返回的結果 QByteArray responseByte = reply->readAll(); QString strRes = responseByte; qDebug() << "Get:" << strRes; QFile file(QDir::currentPath() + "/myResponde.json"); if(!file.open(QIODevice::ReadWrite)) { qDebug() << "File open error"; } file.write(responseByte); file.close(); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); sendPostRequest(); //sendGetRequest(); return a.exec(); }
QT += core gui QT += network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets CONFIG += c++11
Qnetworkutils.h 頭文件
#ifndef QNETWORKUTILS_H #define QNETWORKUTILS_H #include <iostream> #include <QString> #include <QNetworkRequest> using namespace std; namespace QNetWorkUtils { // http請求數據 struct HttpRequestData { HttpRequestData() { strServer = "127.0.0.1"; nPort = 8082; strUrl = ""; } // 重置數據 void Reset() { strServer = "127.0.0.1"; nPort = 8082; strUrl = ""; bytePostData.clear(); mapHeaders.clear(); } QString strServer; int nPort; QString strUrl; QByteArray bytePostData; std::map<QNetworkRequest::KnownHeaders, QVariant> mapHeaders; }; class CMultiPartItem { public: CMultiPartItem(); // 該part為一個字符串,可以指定ContentType和ExContentDisposition CMultiPartItem(const QString& strName, const QString& strValue, const QString& strContentType = "", const QString& strExContentDisposition = ""); // 該part為一個二進制塊,可以指定ContentType(如“image/png”,可省略)和ExContentDisposition(如“filename="123.png"”,必須) CMultiPartItem(const QString& strName, void* pData, int nLen, const QString& strContentType = "", const QString& strExContentDisposition = ""); QString m_sName; QString m_sValue; void* m_pData; int m_nDataLen; QString m_sContentType; QString m_sExContentDisposition; }; typedef std::vector<CMultiPartItem> CMultiPartDatas; //************************************ // 方法: 發送Get請求 // 返回值: bool // 參數: const HttpRequestData & data 請求數據 // 參數: QByteArray & respData 返回響應數據 // 參數: int nTimeoutmsec 請求超時毫秒 //************************************ bool HttpGet( const HttpRequestData& data, QByteArray& respData, int nTimeoutmsec = 30000, QString errMsg = QString(), int* pStatuCode = nullptr); //************************************ // 方法: 發送Post請求 // 返回值: bool // 參數: const HttpRequestData & data 請求數據 // 參數: QByteArray & respData 返回響應數據 // 參數: int nTimeoutmsec 請求超時毫秒 //************************************ bool HttpPost(const HttpRequestData& data, QByteArray& respData, QString& errMsg, int nTimeoutmsec = 30000); //************************************ // 方法: Multipart 數據post上傳 // 返回值: bool // 參數: const QString& strURL 請求URL // 參數: const CMultiPartDatas& multiPartDatas 多部數據集合 // 參數: QByteArray & respData 返回響應數據 // 參數: int nTimeoutmsec bool UploadMultipartData( const QString& strURL, const CMultiPartDatas& multiPartDatas, QByteArray& respData, QString& errMsg, int nTimeoutmsec = 30000); bool UploadMultipartData( const HttpRequestData& data, const CMultiPartDatas& multiPartDatas, QByteArray& respData, QString& errMsg, int nTimeoutmsec = 30000); } #endif // QNETWORKUTILS_H
Qnetworkutils.cpp 源文件
#include "networkutils.h" #include <QNetworkRequest> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QHttpMultiPart> #include <QEventLoop> #include <QTimer> namespace QNetWorkUtils { CMultiPartItem::CMultiPartItem() : m_pData(nullptr), m_nDataLen(0) { } CMultiPartItem::CMultiPartItem(const QString& strName, const QString& strValue, const QString& strContentType /*= ""*/, 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 /*= 30000*/, QString& errMsg, int* pStatuCode /*= nullptr*/) { // 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實現上傳數據”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。