首先必須要先知道POST有四種提交數據的方式分別為以下
詳細的內容可以到https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/700118/了解更多的細節
這邊擷取重點來說明
首先請先參考之前的 ESP32 將數值發佈到 ThingSpeak(最簡單的方法)這篇來註冊ThingSpeak帳號,及了解如何使用
https://karta146831.pixnet.net/blog/post/335164568
了解如何使用ThingSpeak之後先將程式碼複製貼上,並將程式碼中的XXX的部分改成你自己的
範例的內容很簡單,我們選用application/json的方式傳遞給ThingSpeak,一個0-40的亂數,成功之後你會看到持續
接收的數值在圖表構成的點連成的折線圖,就像之前那樣
程式碼:
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "XXXXX"; //輸入你的熱點
const char* password = "XXXXX"; //輸入你的熱點密碼
//Service API Key
String apiKey = "XXXXXXXXXXXXXXXXXX"; //輸入你的API金鑰,可以在ThingSpeak的設置找到,如果找不到請參考前面提到的文章
//Your Domain name with URL path or IP address with path
const char* serverName = "http://api.thingspeak.com/update";
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() {
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(client, serverName); // 輸入你的網址或是IP
/*
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + apiKey + "&field1=" + String(random(40));
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);*/
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
// JSON data to send with HTTP POST
String httpRequestData = "{\"api_key\":\"" + apiKey + "\",\"field1\":\"" + String(random(40)) + "\"}";
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
/*
// If you need an HTTP request with a content type: text/plain
http.addHeader("Content-Type", "text/plain");
int httpResponseCode = http.POST("Hello, World!");
*/
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
delay(5000);
}
程式碼中也包含了其他兩種類型的溝通方式,可以依照自己的需求來使用
分別為application/x-www-form-urlencoded及text/xml
application/x-www-form-urlencoded
text/xml