0

Sorry I am new with this. I am trying to read a JSON response from my website using an ESP8266, but it keeps failing. I am using the following code:

WiFiClientSecure httpsClient;    //Declare object of class WiFiClient
httpsClient.setInsecure();
httpsClient.setTimeout(15000); // 15 Seconds  

if (httpsClient.connect(host, httpsPort)) {

  String Data ="/IOT/Device_Setup.php?MAC="+deviceMAC;
      
  httpsClient.print(String("POST ") + Data + " HTTP/1.1\r\n" +
   "Host: " + host + "\r\n" +               
   "Connection: close\r\n\r\n");

  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    Serial.println(line);
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  String payload = "";    
  while (httpsClient.available()) {        
    char c = httpsClient.read();
    payload=payload+c;
  }

  Serial.println(payload);

  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  StaticJsonDocument<200> jsonBuffer;
  // Parse JSON object
  DeserializationError error = deserializeJson(jsonBuffer, payload);
  if (!error) {

    const char* Switch = jsonBuffer["Switch"];
    const char* LED = jsonBuffer["LED"];
    const char* DHT = jsonBuffer["DHT"];
  
    // Decode JSON/Extract values
    Serial.print("Switch = ");
    Serial.println(Switch);
    Serial.print("LED = ");
    Serial.println(LED);
    Serial.print("DHT = ");
    Serial.println(DHT);
  }
}

When I print out the payload after the header I receive the following output:

22
{"Switch":"0","LED":"0","DHT":"1"}
0

I know the 22 is the hex value for the number of bytes being sent. Is there a way of ignoring the numbers and just using the JSON code?

4
  • how is it failing? – jsotola Mar 8 at 3:25
  • 2
    it is then chunked transfer encoding. set content length on server to avoid it. – Juraj Mar 8 at 6:17
  • Agree, this is Chunked Transfer Encoding, use HTTP/1.0 to avoid it. See also JsonHttpClient.ino on arduinojson.org. – Benoit Blanchon Mar 8 at 8:03
  • 1
    Thanks everyone. Adding the size in the header worked. – Dan Mar 16 at 11:02

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.