如何使用http将字符串发送到ESP32

How to send string to ESP32 using http

我的 python 代码应该发送 "message"

import requests
r = requests.post('http://192.168.0.100:7777',data="Hello")
print(r.text)

我的ESP32代码,我认为问题是因为错误url导致的,因为我不确定我应该在那里使用什么IP。是 python 代码为 运行 的机器的 IP 吗?还是ESP32的IP?还是我完全错了?

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

WebServer server(7777);
HTTPClient http;

const char* ssid = "SSID";
const char* password =  "PASSWORD";

void handleRoot() {
  server.send(200, "text/plain", "Hello World!");
}

void handleNotFound() {
  server.send(404, "text/plain", "Hello World!");
}

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi..");
  }
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);
  server.begin();
  http.begin("http://192.168.0.100/");
}

void loop() {
 server.handleClient();
 int httpCode = http.GET();
 String payload = http.getString();
 Serial.println(httpCode);
 Serial.println(payload);
}

编辑:现在 ESP 应该充当服务器

当您发送 GET/POST 请求时,您必须输入目的地的 IP,在本例中为您的 ESP32 的 IP。

首先要注意的是,我的 server.begin() 默认监听 192.168.4.1:80 作为接入点。

现在,要创建一个异步服务器来保存带有 json 数据的 GET 和 POST 请求,您可以使用如下函数:

文件http_server.h:

#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include "ArduinoJson.h"

#ifndef _HTTP_SERVER_
#define _HTTP_SERVER_

void setup_http_server();

#endif

文件示例 http_server.cpp:

#include "http_server.h"

AsyncWebServer server(80);  // start server listening on port 80
void setup_http_server(){

    // Example of function that holds and HTTP_GET request on 192.168.4.1:80/get_data
    server.on("/get_data", HTTP_GET, [](AsyncWebServerRequest *request){
        // Code that holds the request
        Serial.println("Get received"); // Just for debug
        request->send(HTTP_200_code, "text/plain", "Here I am"); 
    });

    // Example of function that holds and HTTP_POST request on 192.168.4.1:80/set_data
    server.on("/set_data",
        HTTP_POST,
        [](AsyncWebServerRequest * request){},
        NULL,
        [](AsyncWebServerRequest * request, uint8_t *data, size_t len,
        size_t index, size_t total) {
            // Here goes the code to manage the post request
            // The data is received on 'data' variable
            // Parse data
            Serial.printlnt("POST RECEIVED"); // Just for debug
            StaticJsonBuffer<50> JSONBuffer; // create a buffer that fits for you
            JsonObject& parsed = JSONBuffer.parseObject(data); //Parse message
            uint8_t received_data = parsed["number"]; //Get data
            request->send(HTTP_200_code, "text/plain", "Some message");
    });

    server.begin();  // starts asyncrhonus controller
    Serial.println(WiFi.softAPIP());  // you can print you IP yo be sure that it is 192.168.4.1
}

最后,如果您想使用 mobile/computer 直接连接到 ESP32,则需要将其 wifi 连接配置为 ACCESS_POINT。因此,您的 setup()loop() 在您的 main.ino 中可能看起来像:

文件main.ino:

#include "http_server.h"

void setup(){
     Serial.begin(9600);  // setup serial communication
     // Set WiFi to station(STA) and access point (AP) mode simultaneously 
     WiFi.mode(WIFI_AP_STA);
     delay(100); // Recommended delay
     WiFi.softAP("choose_some_ssid", "choose_some_password");

     // Remember to configure the previous server
     setup_http_server();  // starts the asyncronus https server*/
}

void loop(){
     delay(1000);
}

仅此而已。要检查一切是否正常,您可以使用密码 chose_some_password 将您的手机 phone 连接到 wifi choose_some_ssid,打开浏览器并转到 192.168.4.1/get_data,您应该会看到 "Here I am" 作为回应。

正如你在问题中所说,如果你想发送 post 和 python 你可以这样做:

import requests
r = requests.post('http://192.168.4.1:80/set_data', data="{'number':55}") // remember that you get the keyword 'number' in the server side
print(r.text) // should print "Some message"

可以在 https://techtutorialsx.com/2018/10/12/esp32-http-web-server-handling-body-data/ 上找到更多信息 希望对您有所帮助!