ESP8266-Arduino网络编程实例-简单HTTP数据请求(基于Node-Red)

简单HTTP数据请求

超文本传输协议 (HTTP) 用作客户端和服务器之间的请求-响应协议。本实例将演示如何通过ESP8266发起一个HTTP请求,向远程主机请求数据。

在开始本实例之前,首先准备一个可用的HTTP服务器,或一个可用的HTTP URL。在这里,通过Node-Red物联网编程环境创建一个数据请求节点。Node-Red安装步骤如下:

  • 下载并安装node.js
  • 在命令行中运行

npm -g install node-red

  • 在Node-Red安装完成后,在命令行中运行:

node-red

启动Node-Red服务器,Node-Red默认端口为1880

  • 接着,在浏览器打开Node-Red

http://localhost:1880

  • 最后创建运行节点,并创建一个时间请求流程:

在这里插入图片描述

在函数节点中,输入如下代码:

1
2
3
4
5
6
// Create a Date object from the payload
var date = new Date();
// Change the payload to be a formatted Date string
msg.payload = date.toString();
// Return the message so it can be sent on

如果不太熟悉操作的,可以复制本实例的节点代码导入即可:

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": "60551d068a09952f",
"type": "http in",
"z": "65febd16d6c14bb0",
"name": "date\_time\_request",
"url": "/date\_time",
"method": "get",
"upload": false,
"swaggerDoc": "",
"x": 270,
"y": 140,
"wires": [
[
"764de1bfd43df11a"
]
]
},
{
"id": "764de1bfd43df11a",
"type": "function",
"z": "65febd16d6c14bb0",
"name": "",
"func": "// Create a Date object from the payload\nvar date = new Date();\n// Change the payload to be a formatted Date string\nmsg.payload = date.toString();\n// Return the message so it can be sent on\nreturn msg;",
"outputs": 1,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 450,
"y": 140,
"wires": [
[
"12b4b3fbbe4b272e",
"bc6ef9d8bbc1208d"
]
]
},
{
"id": "12b4b3fbbe4b272e",
"type": "http response",
"z": "65febd16d6c14bb0",
"name": "http(200)",
"statusCode": "",
"headers": {},
"x": 680,
"y": 100,
"wires": []
},
{
"id": "bc6ef9d8bbc1208d",
"type": "debug",
"z": "65febd16d6c14bb0",
"name": "msg.payload",
"active": true,
"tosidebar": true,
"console": true,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"statusVal": "",
"statusType": "auto",
"x": 700,
"y": 160,
"wires": []
}
]

最后,点击右上角的部署Deploy按钮,完成流程部署。

  • ESP8266(客户端)向运行 Node-RED服务器提交 HTTP 请求;
  • Node-RED服务器向 ESP8266(客户端)返回响应;
  • 最后,响应包含有关请求的状态信息,也可能包含请求的内容。

ESP8266作为HTTP客户端,发起HTTP Get请求的代码如下:

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
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

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

// HTTP请求URL
String serverName = "http://192.168.0.164:1880/date\_time";

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

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) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;

String serverPath = serverName + "?temperature=24.37";

// 启动HTTP请求
http.begin(client, serverPath.c\_str());

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

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

示例代码如何运行?

1)导入依赖头文件

1
2
3
4
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

2)启动WiFi连接

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

3)发起HTTP请求

1
2
3
4
5
6
7
8
WiFiClient client;
HTTPClient http;

String serverPath = serverName + "?temperature=24.37";

// 启动HTTP请求
http.begin(client, serverPath.c\_str());

4)处理HTTP请求响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 查询HTTP请求的响应状态
int httpResponseCode = http.GET();

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

5)释放HTTP请求占用资源

1
2
http.end();

运行结果如下:

在这里插入图片描述

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