? ? ? ? 由于项目要求向服务器平台提供的api接口发送特定格式的json数据,本地客户端处理后向其发送,首先是用postman模拟了一下上传的效果,以及查看返回的状态码判断上传是否成功。
//json格式示例
[
{
"device_id": "CJ02A-2110051",
"sensorArray": [50,60],
"upload_time": "2021-12-07 17:00:00"
}
]
?????????从结构上判断主要是{}数组[ ]里面包含了1个object对象{ },然后这个object对象里包含了3个
参数,参数里“sensorArray”也是一个数组。代码如下:
QString device_id = "CJ02A-2110051";
QString upload_time = "2021-12-12 20:00:00";
float Temperature = 15.30;
float Humidity = 70.34;
QJsonArray TH;
TH.append(Temperature);
TH.append(Humidity);
QJsonObject json;//构建json对象json
json.insert("device_id", device_id);
json.insert("sensorArray",QJsonValue(TH));
json.insert("upload_time", upload_time);
QJsonArray JSON;
JSON.append(QJsonValue(json));
QJsonDocument document;
document.setArray(JSON);
QByteArray byte_array = document.toJson(QJsonDocument::Indented);//Compact
QString json_str(byte_array);
ui->textEdit_3->setText(json_str);
//http请求
QNetworkRequest request1;
QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
QMetaObject::Connection connRet = QObject::connect(naManager,SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
Q_ASSERT(connRet);
request1.setUrl(QUrl("http://iot.joinken.cn/nyy/admin/hd/hd_device/analogDeviceData"));
request1.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
QString token= "Bearer eyJhbGciOiJIUzUxMiJ8";
QString token_headerData = token;
request1.setRawHeader("Authorization",token_headerData.toLocal8Bit());
QNetworkReply* reply = naManager->post(request1, byte_array);
?这里的函数主要是用来返回状态码查看上传情况。
void MainWindow::requestFinished(QNetworkReply* reply) {
// 获取http状态码
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid())
qDebug() << "status code=" << statusCode.toInt();
QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
if(reason.isValid())
qDebug() << "reason=" << reason.toString();
QNetworkReply::NetworkError err = reply->error();
if(err != QNetworkReply::NoError) {
qDebug() << "Failed: " << reply->errorString();
}
else {
// 获取返回内容
qDebug() << QString::fromLocal8Bit(reply->readAll());
}
}
|