POST 从我的 ESP8266 到 REST API

POST to REST API from my ESP8266

我做了一个 REST API,我想从我的 ESP8266 向其中一个端点发出 post 请求,但我做不到。

到目前为止循环内的代码:

HTTPClient http;    //Declare object of class HTTPClient



http.begin("http://localhost:5000/api/users/5b1e82fb8c620238a85646fc/arduinos/5b243dc666c18a2e10eb4097/data");
   http.addHeader("Content-Type", "text/plain");
   http.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViMWU4MmZiOGM2MjAyMzhhODU2NDZmYyIsImlhdCI6MTUyOTEwMTc5MiwiZXhwIjoxNTI5MTE2MTkyfQ.2O6knqriuFoEW9C2JQKRlM3D0DNnzqC7e7gpidy3pWU");
http.end(); 

问题是我不知道如何设置请求的主体。

它应该是一个 json,带有一个名为 "value" 的键。例如:

{
"value":101
}

有人知道怎么做吗?我也可能应该使用 ip 而不是 "localhost".

提前致谢。

使用 ArduinoJsonhere。然后您可以构建您的 HTTP 正文。

StaticJsonBuffer<300> JSONbuffer;   //Declaring static JSON buffer
JsonObject& JSONencoder = JSONbuffer.createObject();

JSONencoder["value"] = value_var;
char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));

HTTPClient http;    //Declare object of class HTTPClient

http.begin("API end point here");      //Specify request destination
http.addHeader("Content-Type", "application/json");  //Specify content-type header

int httpCode = http.POST(JSONmessageBuffer);   //Send the request
String payload = http.getString();                  //Get the response payload

然后使用上面的示例代码封装JSON发送到API端点