在 ESP32 上发送 POST 请求
时间: 2024-06-09 14:10:55 浏览: 233
要在ESP32上发送POST请求,您需要使用ESP32的WiFi功能连接到互联网,并使用HTTP客户端库发送POST请求。下面是一个示例代码,可以在ESP32上使用Arduino IDE进行编写和上传:
```c
#include <WiFi.h>
#include <HTTPClient.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Your Domain name with URL path or IP address with path
const char* serverName = "http://yourdomain.com/api/post_data";
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Use WiFiClient class to create TCP connections
WiFiClient client;
HTTPClient http;
Serial.print("[HTTP] begin...\n");
// configure server and url
http.begin(client, serverName);
Serial.print("[HTTP] POST...\n");
// start connection and send HTTP header
int httpResponseCode = http.POST("Hello World");
// httpCode will be negative on error
if (httpResponseCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] POST... code: %d\n", httpResponseCode);
// file found at server
if (httpResponseCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpResponseCode).c_str());
}
http.end();
delay(10000);
}
```
将上面的示例代码中的“your_SSID”和“your_PASSWORD”替换为您的WiFi网络凭据,并将“serverName”替换为您要发送POST请求的URL或IP地址。然后,您可以上传并运行代码,ESP32将连接到WiFi网络并发送POST请求。
阅读全文