api - 从我的 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”。
提前致谢。
解决方案
在此处使用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 端点。
推荐阅读
- python - 如何在 python 的 exe.file 中包含 sqlite 数据库?
- java - 我们可以在 NestJS 中同时拥有缓存名称和缓存键吗?
- python - 使用 mpmath.runtests() 测试失败
- mongodb - 如何使用 mongo 聚合添加自定义字段?
- rust - 包含来自另一个 toml 的 toml 文件
- scilab - xcos 数据类型维度的含义
- c# - 为什么 ChartJs.Blazor 有错误(更改 ASPNETCORE_ENVIRONMENT)
- javascript - 在 React Native 中的 TextInput 中使文本可点击
- sql - 我们可以使用唯一键作为主键吗?
- android - 如何在颤动中创建具有多行的行