每次我从 android 应用程序向 esp32 模块发送数据时,它都会以“EmptyInput”的形式到达

Every time I send data from android app to esp32 module, it arrives as an "EmptyInput"

提问人:Lemuel Mojica Vázquez 提问时间:10/22/2023 更新时间:10/23/2023 访问量:30

问:

我需要将 json 格式的数据从 android 应用程序发送到 esp32 wifi 模块(“arduino”)。

android 应用程序以正确的 json 格式成功发送数据...ESP32 模块知道它接收到一些东西,但它总是作为空输入到达,并因此给我一个错误。

另一方面,当我从 flask 服务器向 esp32 模块发送/接收数据时,它工作正常。与从 flask 服务器向 android 应用程序发送/接收数据相同...有什么建议,或者我在两者之间做错了什么?

这是课堂“大项目”的一部分,并且已经工作了 2 个多月,所以我真的需要它在这里工作。谢谢!

我尝试发送简单的字符串,例如“hey”,其中内容类型设置为“plain”,它仍然作为空字符串到达 esp32......

我在 esp32 模块中有以下内容:

#include <ArduinoJson.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <HTTPClient.h>
#include "AsyncJson.h"

const char* ssid = "wifi_ssid";                //changed these for the post
const char* password = "wifi_password";        //changed these for the post
const unsigned long connectionTimeout = 10000;

AsyncWebServer server(80);

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

  Serial.print("Connecting to Wifi...");

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.print("Connected to WiFi. IP address: ");
  Serial.println(WiFi.localIP());

  //other code stuff...

  // Start server
  //other server.on() stuff...
  server.on("/brew_coffee", HTTP_POST, handleBrewCoffee);
  
  server.begin();
}

void handleBrewCoffee(AsyncWebServerRequest *request) {
  if (request != nullptr) {

    String clientIPAddress = request->client()->remoteIP().toString();

    // Here I receive the data and print it
    String recipeReceived = request->arg("application/json");
    Serial.print("\n" + clientIPAddress);
    Serial.print(" sent string: ");
    Serial.println(recipeReceived);

    DynamicJsonDocument jsonDoc(16386);
    DeserializationError error = deserializeJson(jsonDoc, recipeReceived);

    //This is where I get the EmptyInput error
    if (error) {
      Serial.print("Failed to parse JSON: ");
      Serial.println(error.c_str());
      recipeReceived = "not: " + clientIPAddress;

    } else{
        //Extracting json data
        const char* username = jsonDoc["username"];
        const char* user_ip = jsonDoc["user_ip"];
        const char* user_id = jsonDoc["user_id"];
        const char* name = jsonDoc["name"];
        //I do rest of the data likewise

        // Print the coffee information
        Serial.println("\nCoffee Information:");
        Serial.print("username: "); Serial.println(username);
        Serial.print("user_id: "); Serial.println(user_id);
        Serial.print("Coffee Name: "); Serial.println(name);
        //I do rest of the data likewise
        
        recipeReceived = "Coffee Received";
      }
  }
}

这是我的android应用程序(来自android studio)中发送数据的函数:

    public String makeServiceCallPostJSON(String reqUrl, String username, String user_ip, int user_id, String name, more params...) {

        String response = null;
        try {

            //This url is the same as the esp32 with its proper endpoint
            URL url = new URL(reqUrl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");

            JSONObject jsonParams = new JSONObject();
            jsonParams.put("username", username);
            jsonParams.put("user_ip", user_ip);
            jsonParams.put("user_id", user_id);
            jsonParams.put("name", name);
            //I do rest likewise


            conn.setRequestProperty("Content-Type", "application/json");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            System.out.println(jsonParams.toString());

            conn.getOutputStream().write(jsonParams.toString().getBytes("UTF-8"));

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            // Convert the InputStream in a String
            response = convertStreamToString(in);

            System.out.println("This is what i got... " + response);

        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

这是我在 esp32 模块中得到的输出

###.#(客户端地址)发送的字符串: 无法解析 JSON:EmptyInput

这些是我在 android studio 的 Logcat 中获得的打印件

{“username”:“guest”,“user_ip”:“###.###.#.###”,“user_id”:1,“name”:“咖啡B”, ...} 这就是我得到的......不

user_ip与 esp32 输出中打印的客户端地址相同。这进一步证明了它“接收”了一些东西,即使它是空的......

java android json http-post esp32

评论

0赞 ChipChop Gizmo 10/22/2023
我会首先尝试打印整个“请求”,看看它是如何形成的,或者更准确地说,ESPAsyncWebServer.h 是如何格式化“args”键:值的。你可能会发现 json 已经在 args 中拆分为类似 request->arg(“username”), request->arg(“user_id”)
0赞 Lemuel Mojica Vázquez 10/23/2023
我尝试了你的建议,也没有用......但我刚刚找到了另一种方法来做到这一点,它现在起作用了......我现在正在使用 WebServer.h,没有任何问题......使用起来也有点简单。

答:

0赞 Lemuel Mojica Vázquez 10/23/2023 #1

出于某种原因,以下库在尝试将某些内容从移动应用程序发送到 esp32 时总是给我一个空字符串: ESP8266Web服务器 AsyncWebServer_ESP32_W5500 ESPAsyncWebServer ESPAsyncWebSrv

注意:这些在与其他东西(例如python中的烧瓶服务器)通信时有效...我仍然不知道移动应用程序有什么问题。

这个与移动应用程序和烧瓶服务器完美配合......除了对以下库的微小 sintax 更改外,我并没有真正改变我正在做的事情: 网络服务器

下面是它的样子:

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

String ssid = "wifi_ssid";
String password = "wifi_password";
WebServer server(80);

void setup(){

    Serial.print("Connecting to Wifi...");
    
    // Connect to Wi-Fi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    
        Serial.print(".");
        delay(1000);
    
    }
    
    server.on("/brew_coffee", HTTP_POST, handleBrewCoffee);
    server.begin();

}

void handleBrewCoffee() {

    if (server.hasArg("plain")) {

        String recipeReceived = server.arg("plain");
        Serial.println("Received JSON data:");
        Serial.println(recipeReceived);
        DynamicJsonDocument jsonDoc(1024);
        DeserializationError error = deserializeJson(jsonDoc, recipeReceived);

        if (error) {

            Serial.print("Failed to parse JSON: ");
            Serial.println(error.c_str());
            recipeReceived = "not";
    
        } else{

            const char* username = jsonDoc["username"];
            //same for the rest
    
            Serial.println("Coffee Information:");
            Serial.print("username: "); Serial.println(username);
            //same for the rest
      
            recipeReceived = "Coffee Received";

        }

        server.send(200, "text/plain", recipeReceived);

    }

}