1.url编码形式Post数据
示例代码
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///please enter your sensitive data in the Secret tab/arduino_secrets.h
/// Wifi Settings ///
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char serverAddress[] = "192.168.0.3"; // server address
int port = 8080;
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making POST request");
String contentType = "application/x-www-form-urlencoded";
String postData = "name=Alice&age=12";
client.post("/", contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}
2.JSON格式Post数据
示例代码
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
void setup() {
Serial.begin(115200); //Serial connection
WiFi.begin("UU", "1212312121"); //WiFi connection
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
delay(500);
Serial.println("Waiting for connection");
}
}
void loop() {
int sensor_value = 45;
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
String json = "{\"sensor\":\"gps\",\"value\":\""+ String(sensor_value) +"\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
DynamicJsonBuffer jsonBuffer;
char postMessage[300];
JsonObject& root = jsonBuffer.createObject();
JsonObject& Jarray = jsonBuffer.parseObject(json);
root["name"] = "lll";
root["content"] = Jarray;
root.printTo(postMessage,sizeof(postMessage));
Serial.print(postMessage);
//----------------------------------------------------------
HTTPClient http;
http.begin("http://iot.data.ubu.ac.th/api/save" );
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(postMessage);
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
}
else {
Serial.println("Error in WiFi connection");
}
delay(3000); //Send a request every 30 seconds
}
通过api接口post数据,数据格式可以有url编码,json格式,text文本格式,表单参数等各种形式,有些接口不限制数据格式,有些会限制,比如只允许JSON格式