用QT做一個客戶端來調用客戶的接口,利用到了https協議。先對post做下記錄
- 首先在pro文件中添加
QT += network
- 然後頭文件中添加
#include <QNetworkAccessManager> //加載網絡請求頭文件
#include <QNetworkReply>
#include <QNetworkRequest> //加載發送請求頭文件
#include <QEventLoop>
- 代碼示例
void LibRSAClient::MessagePost(std::string strCiphertext)
{
QByteArray post_data;
QNetworkRequest network_request;
QString strAnd = "&";
QString strDeviceID, strDetectID, strProduct, strModel, strIMEI, strPicPath, strStartTime, strEndTime, strData;
//設置發送的數據
strDeviceID = "device_id=" + QString::fromStdString(m_sDefect.strDeviceID) + strAnd;
strDetectID = "detect_id=" + QString::fromStdString(m_sDefect.strDetectID) + strAnd;
strProduct = "product=" + QString::fromStdString(m_sDefect.strProduct) + strAnd;
strModel = "model=" + QString::fromStdString(m_sDefect.strModel) + strAnd;
strIMEI = "imei=" + QString::fromStdString(m_sDefect.strimei) + strAnd;
strPicPath = "pic_path=" + QString::fromStdString(m_sDefect.strImagePath) + strAnd;
strStartTime = "start_time=" + QString::fromStdString(m_sDefect.strStartTime) + strAnd;
strEndTime = "end_time=" + QString::fromStdString(m_sDefect.strEndTime) + strAnd;
strData = "data=" + QString::fromStdString(strCiphertext) + strAnd;
post_data.append(strDeviceID);
post_data.append(strDetectID);
post_data.append(strProduct);
post_data.append(strModel);
post_data.append(strIMEI);
post_data.append(strPicPath);
post_data.append(strStartTime);
post_data.append(strEndTime);
post_data.append(strData);
//設置頭信息
network_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
network_request.setHeader(QNetworkRequest::ContentLengthHeader, post_data.length());
//設置url
network_request.setUrl(m_url);
QEventLoop loop;
QNetworkAccessManager *manage = new QNetworkAccessManager(); //分配空間
//發送請求
while(true)
{
QNetworkReply* pReply = manage->post(network_request, post_data);
connect(pReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
// 獲取發送的返回結果
QNetworkReply::NetworkError err = pReply->error();
if(err == QNetworkReply::NoError)
{
QString strResult = pReply->readAll();
//qDebug() << "Result: " << strResult;
if(strResult.contains("succ"))
{
qDebug() << "post success";
pReply->deleteLater();
pReply = nullptr;
break;
}
else
{
qDebug() << "post fail";
pReply->deleteLater();
pReply = nullptr;
continue;
}
}
}
}
- 上面用到了QEventLoop類,其爲我們提供了一種進入和退出一個事件循環的方法。在任何時候,你都可以創建一個QEventLoop實例,然後調用exec()來啓動一個事件循環,在這個循環期間,可以調用exit()或者quit()來使exct()返回。 故當pReply返回finish信號時,loop會退出。