ESP8266-Arduino网络编程实例-HTTP请求JSON数据及解析

HTTP请求JSON数据及解析

在前面的文章ESP8266-Arduino网络编程实例-简单HTTP数据请求(基于Node-Red) 中,我们实现了简单的HTTP数据请求,在这里,我们将实现通过HTTP请求JSON类型数据,并对请求结果进行解析。本次实例继续使用Node-Red作为HTTP服务器。

在这里插入图片描述

在Node-Red中创建了一个流程,一个get-sensor节点,该节点响应HTTP请求,并返回JSON数据。在函数模块中添加如下代码:

1
2
3
msg.payload = {"value1":24.25, "value2":49.54, "value3":1005.14};
return msg;

流程的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
[
{
"id": "6530621.95b429c",
"type": "http in",
"z": "65febd16d6c14bb0",
"name": "",
"url": "/get-sensor",
"method": "get",
"upload": false,
"swaggerDoc": "",
"x": 280,
"y": 420,
"wires": [
[
"9471d1a0.68588"
]
]
},
{
"id": "5ddc9f47.4b555",
"type": "http response",
"z": "65febd16d6c14bb0",
"name": "",
"statusCode": "200",
"headers": {},
"x": 640,
"y": 380,
"wires": []
},
{
"id": "9471d1a0.68588",
"type": "function",
"z": "65febd16d6c14bb0",
"name": "",
"func": "msg.payload = {\"value1\":24.25, \"value2\":49.54, \"value3\":1005.14};\nreturn msg;",
"outputs": 1,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 470,
"y": 429,
"wires": [
[
"5ddc9f47.4b555",
"13aea59.7430e5a"
]
]
},
{
"id": "13aea59.7430e5a",
"type": "debug",
"z": "65febd16d6c14bb0",
"name": "",
"active": true,
"tosidebar": true,
"console": true,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"statusVal": "",
"statusType": "auto",
"x": 660,
"y": 448,
"wires": []
}
]

在前面的文章中,我们对Arduino的JSON格式数据处理作为了详细的解析,主参考:

本次实例使用的JSON解析为Arduino_Json

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Arduino\_JSON.h>

const char\* ssid = "\*\*\*\*\*"; // WIFI名称
const char\* password = "\*\*\*\*\*"; // WIFI密码

// HTTP请求URL
const char\* serverName = "http://192.168.0.164:1880/get-sensor";


unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

String sensorReadings;
float sensorReadingsArr[3];

void setup() {
Serial.begin(115200);

WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());

Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
// 每5秒发起一次请求
if ((millis() - lastTime) > timerDelay) {
// 检查WiFi状态
if(WiFi.status()== WL_CONNECTED){
// 请求JSON数据
sensorReadings = httpGETRequest(serverName);

Serial.println(sensorReadings);

// 解析JSON数据
JSONVar myObject = JSON.parse(sensorReadings);
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}

Serial.print("JSON object = ");
Serial.println(myObject);
JSONVar keys = myObject.keys();

for (int i = 0; i < keys.length(); i++) {
JSONVar value = myObject[keys[i]];
Serial.print(keys[i]);
Serial.print(" = ");
Serial.println(value);
sensorReadingsArr[i] = double(value);
}
Serial.print("1 = ");
Serial.println(sensorReadingsArr[0]);
Serial.print("2 = ");
Serial.println(sensorReadingsArr[1]);
Serial.print("3 = ");
Serial.println(sensorReadingsArr[2]);
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

String httpGETRequest(const char\* serverName) {
WiFiClient client;
HTTPClient http;

// 发起HTTP请求
http.begin(client, serverName);

// 查询HTTP请求响应状态码
int httpResponseCode = http.GET();

String payload = "{}";

if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// 释放HTTP
http.end();

return payload;
}

首先,导入相关依赖头文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Arduino\_JSON.h>

const char\* ssid = "\*\*\*\*\*"; // WIFI名称
const char\* password = "\*\*\*\*\*"; // WIFI密码

// HTTP请求URL
const char\* serverName = "http://192.168.0.164:1880/get-sensor";


unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

String sensorReadings;
float sensorReadingsArr[3];

接着,在setup函数中,初始化WiFi及连接:

1
2
3
4
5
6
7
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

接着,在loop函数中,发起HTTP请求:

1
2
3
// 请求JSON数据 
sensorReadings = httpGETRequest(serverName);

其中httpGETRequest函数实现对HTTP请求进行封装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
String httpGETRequest(const char\* serverName) {
WiFiClient client;
HTTPClient http;

// 发起HTTP请求
http.begin(client, serverName);

// 查询HTTP请求响应状态码
int httpResponseCode = http.GET();

String payload = "{}";

if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// 释放HTTP
http.end();

return payload;
}

在请求完成之后,对服务响应数据进行解析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 解析JSON数据
JSONVar myObject = JSON.parse(sensorReadings);
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}

Serial.print("JSON object = ");
Serial.println(myObject);
JSONVar keys = myObject.keys();

for (int i = 0; i < keys.length(); i++) {
JSONVar value = myObject[keys[i]];
Serial.print(keys[i]);
Serial.print(" = ");
Serial.println(value);
sensorReadingsArr[i] = double(value);
}
Serial.print("1 = ");
Serial.println(sensorReadingsArr[0]);
Serial.print("2 = ");
Serial.println(sensorReadingsArr[1]);
Serial.print("3 = ");
Serial.println(sensorReadingsArr[2]);

运行结果如下:

在这里插入图片描述

文章来源: https://iotsmart.blog.csdn.net/article/details/127179606