0

I'm sending an HTTP Post request on my Android App to my Wemos D1 mini pro and want to parse the incoming data (which is a json). My current code just prints out the whole POST request and I need to trim it so I only get the needed data. There are several examples out there but nothing matched my needs or worked at all.

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




const char* ssid = "myssid";
const char* password = "mypassword";
char c;
String readString = String(100);
WiFiServer wifiServer(80);


void setup() {

  Serial.begin(9600);
  delay(1000);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }

  Serial.print("Connected to WiFi. IP:");
  Serial.println(WiFi.localIP());
  wifiServer.begin();

}


//for parsing the actual JSON later  
//you can ignore this at this moment because I don't even get the needed string to parse it from JSON
void handleReceivedMessage(String message){

  StaticJsonBuffer<500> JSONBuffer;                     //Memory pool
  JsonObject& parsed = JSONBuffer.parseObject(message); //Parse message

  if (!parsed.success()) {   //Check for errors in parsing

    Serial.println("Parsing failed");
    return;

  }

  const char * name3 = parsed["name"];           //Get name from HTTP
  Serial.println("name3");
}


void loop() {
  WiFiClient client = wifiServer.available();


  if (client) {
  Serial.println("Client connected");


    while (client.connected()) {

      while (client.available()>0) {
        //instream from mobile device

        char c = client.read();
        if (readString.length() < 100) {

         //store characters to string
         readString.concat(c);
         //Serial.print(c);
}
      Serial.print(c);
//if HTTP request has ended
       if (c == '\n') {
          //Serial.println(readString);   
          delay(50);  
          //handleReceivedMessage(readString);         
          readString = "";
          client.stop();
   }
 }}}}
  • 1
    the request has a protocol part and the payload. the HTTP headers end with an empty line. then the payload, your json string, follows. the ArduinoJson can only process valid JSON, but you feed it with the complete HTTP request. a valid code would parse the headers line by line, read the content-length header and then use this length to read the payload.but a simple version could simply skip the header with client.find("\r\n\r\n"), like in this example github.com/jandrassy/WiFiEspAT/blob/… – Juraj Aug 13 '19 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.