使用esp32发送HTTP POST请求时出现问题

时间:2020-08-12 09:28:11

标签: post httpclient esp32

我正在努力从ESP32向本地Web服务器发送POST请求。

使用邮递员发送请求,以下工作正常。

POST /save.php? HTTP/1.1
Host: 192.168.0.25
Content-Type: application/x-www-form-urlencoded
Cookie: PHPSESSID=6ad40ac58475ce63ebc6454178d52601

data=[{"name":"val1","value":"5"}]

下一步,我尝试让ESP32发送请求。为此,我改编了HTTPClient示例:

#include "WiFi.h"
#include <HTTPClient.h>

// WLAN Infos
const char* WIFI_SSID = "mySSID";
const char* WIFI_PASSWORD = "myPWD"; 
HTTPClient http;


void setup() {
 // connect to wifi. 
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());         // Send the IP address of the ESP8266 to the computer
}

void loop() {

  String postData = "[{\"name\":\"val1\",\"value\":\"5\"}]";  

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status  
    Serial.println("WiFi connected");
    http.begin("192.168.0.25/save.php?"); 

    http.addHeader("Content-Type", "application/x-www-form-urlencoded");  
    http.addHeader("Cookie", "PHPSESSID=6ad40ac58475ce63ebc6454178d52601");

    int responseCode = http.POST(postData);

    Serial.print("responding with code: ");
    Serial.println(responseCode);

    if (responseCode > 0) {
      String payload = http.getString();   
      Serial.println(payload);
    }

    http.end();
 
  }

  delay(5000);
}

WiFi成功连接后,responseCode为-1。 我被这个问题困扰了一个星期。 您知道导致问题的原因以及如何解决该问题吗?

谢谢!

0 个答案:

没有答案
相关问题