ESP8266在Django Webapp中的POST请求上返回代码400

问题描述

我将Django Web应用程序部署到了Internet,但是我无法POST请求数据,因为它正在返回 HTTP CODE 400, const char* serverName = "https://example.com/api/v1/post_sample"; =返回400个代码。

但是当我这样做时:const char* serverName = "http://localhost:8000/api/v1/post_sample";可以工作并返回201代码。

它目前未在Web应用程序上施加任何限制或身份验证。我什至在Postman上向部署的Web应用程序发出了POST请求,该请求也有效。

请帮助。谢谢!

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

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";


const char* serverName = "https://example.com/api/v1/post_sample";


unsigned long lastTime = 0;
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() {
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;
      
      http.begin(serverName);

      http.addHeader("Content-Type","application/json");
      int httpResponseCode = http.POST("{\"value\":\"1\"}");
     
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
        
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

解决方法

  1. 在尝试建立http连接之前,您没有建立WiFiClient

  2. 对于使用ESP8266HTTPClient的POST请求,当您使用已建立的客户端实例建立http.begin(client,url)时,您将传入URL。请参见example代码。您的情况应该是:

    if(WiFi.status()== WL_CONNECTED){
       WiFiClient client;
       HTTPClient http;
    
       http.begin(client,serverName);
    
       http.addHeader("Content-Type","application/json");
       int httpResponseCode = http.POST("{\"value\":\"1\"}");
    
       Serial.print("HTTP Response code: ");
       Serial.println(httpResponseCode);
    
       http.end();
     }
     else {
       Serial.println("WiFi Disconnected");
     }
    
  3. 如果您的网址是与示例网址中所示的与https的安全连接,那么您将需要使用<WiFiClientSecureBearSSL.h>之类的库来建立安全客户端。参见example

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...