通过 arduino 发送 POST 请求到 PHP 文件

Sending POST request to PHP file via arduino

我正在尝试将温度读数发送到我网站中的 php 文件。但是,似乎没有传递温度变量。下面我使用以下 Arduino 代码:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define SERVER_IP "XXX.XX.XXX.XX"

#ifndef STASSID
#define STASSID "XXX"
#define STAPSK  "XXX"
#endif

void setup() {
  Serial.begin(115200);
  Serial.println();  Serial.println();  Serial.println();
  WiFi.begin(STASSID, STAPSK);

  while (WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.print(".");  }
  Serial.println("");  Serial.print("Connected! IP address: ");  Serial.println(WiFi.localIP());
}

void loop() {
  if ((WiFi.status() == WL_CONNECTED)) {
    WiFiClient client;
    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    http.begin(client, "http://" SERVER_IP "/device.php"); //HTTP
    http.addHeader("Content-Type", "application/json");

    Serial.print("[HTTP] POST...\n");
    int httpCode = http.POST("{\"temp\":\"15\"}");

    if (httpCode > 0) {
      Serial.printf("[HTTP] POST... code: %d\n", httpCode);

      if (httpCode == HTTP_CODE_OK) {
        const String& payload = http.getString();
        Serial.println("received payload:\n<<");
        Serial.println(payload);
        Serial.println(">>");
      }
    } else {
      Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();
  }

  delay(100000);
}

在我的 device.php 中使用以下代码:

<?php header('Content-type: application/json'); header('Content-Type: text/html; charset=utf-8'); require 'config.php'; 
 header("Access-Control-Allow-Origin: *");

    $temp = $_POST["temp"];
    $ins = mysqli_query($link,"INSERT INTO `test`(`id`,`test`)VALUES(NULL,'$temp')");
        
    $responseArray = array('status' => $_POST);         
    $encoded = json_encode($responseArray);     header('Content-Type: application/json');   echo $encoded;

?>

但是,我最终得到 php 错误提示:

PHP Notice:  Undefined index: temp in /var/www/html/device.php on line 6

我在 mysql 中得到空条目,串行监视器显示空负载:

[HTTP] begin...
[HTTP] POST...
[HTTP] POST... code: 200
received payload:
<<
{"status":[]}
>>

根据 Tangentially Perpendicular 评论的解决方案是将内容类型 header 更改为

    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

并将数据发布到

    int httpCode = http.POST("temp=15");