【发布时间】:2021-09-07 22:27:08
【问题描述】:
我想询问有关将数据从 arduino/esp 发送到运行在 Azure 上的 .net App 服务的问题。 我正在向 API 发送带有“测量”“列表”的 JSON(简单的 JSON、ID 和值)。
在 PostMan 上我没有任何问题,但在 Arduino 上我面临收到结果代码 415 的问题。 数据以 JSON 格式发送。
Arduino 代码:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char* ssid = "*******";
const char* password = "*******";
//Your Domain name with URL path or IP address with path
const char* serverName = "https://********.azurewebsites.net/api/Measurements/";
unsigned long lastTime = 0;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
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() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED)
{
std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
client->setInsecure();
HTTPClient https;
https.addHeader("Content-Type", "application/json"); // tried even "text/json"
//https.addHeader("Content-Length", "32");
https.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
https.addHeader("Host","******.azurewebsites.net");
https.addHeader("Cache-Control","no-cache");
String httpRequestData = "[{\"SensorId\": 1, \"Value\": 77.7}]";
if (https.begin(*client, serverName))
{
Serial.print("[HTTPS] POST...\n");
int httpCode = https.POST(httpRequestData);
if (httpCode > 0)
{
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTPS] POST... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY)
{
String payload = https.getString();
Serial.println(payload);
}
else
{
Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
}
}
else
{
Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
}
https.end();
}
else
{
Serial.printf("[HTTPS] Unable to connect\n");
}
}
lastTime = millis();
}
}
没有收到任何错误,只是响应代码 415。
HTTP 415 Unsupported Media Type 客户端错误响应码表示服务器拒绝接受请求,因为payload
JSON 文本:
[{"SensorId": 1, "Value": 77.7}]
以及来自 AppInsight 的报告:
应用服务:
通过 PostMan,我可以访问 azure 并发送数据,但通过 Arduino,我无法发送数据(我能够获取数据,但不能发布)
可能是一些初学者的错误。 有人可以给我提示吗? 我的 JSON 格式是否错误?
【问题讨论】:
-
你的代码在我看来没问题。我建议您在 azure 应用程序中记录您的请求。从那里您可以看到 arduino 和邮递员请求之间的不同之处。类似stackoverflow.com/a/67510839/5964792
-
如果你使用这个会怎样:
https.addHeader("Accept", "application/json");。您正在发布 JSON,我认为您也应该接受它。我在您的请求中没有看到这一点。