首页 > 解决方案 > 从我的 ESP8266 POST 到 REST API

问题描述

我已经制作了一个 REST API,我想从我的 ESP8266 向其中一个端点发出发布请求,但我无法做到。

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

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(); 

问题是我不知道如何设置请求的正文。

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

{
"value":101
}

有谁知道该怎么做?我也可能应该使用 ip 而不是“localhost”。

提前致谢。

标签: apipostarduinoesp8266

解决方案


在此处使用ArduinoJson库。然后您可以构建您的 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 端点。


推荐阅读