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上传数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章