What is ESP8266HTTPClient?
ESP8266HTTPClient is an HTTP library provided with the ESP8266 core for Arduino. It allows performing HTTP requests on an ESP8266-based board, including Adafruit Feather HUZZAH, NodeMCU, SparkFun ESP8266 Thing, Lolin D1 Mini Pro, and many more.
Assuming that the board is connected to the WiFi network, you can send an HTTP request like that:
HTTPClient http; // Send request http.begin("http://arduinojson.org/example.json"); http.GET(); // Print the response Serial.print(http.getString()); // Disconnect http.end();
See BasicHttpClient.ino for a complete example.
How to parse a JSON document from an HTTP response?
We could pass the result of
http.getString() directly to
deserializeJson(), but it would be quite inefficient because it would copy the complete response in RAM before parsing.
We can do much better by letting ArduinoJson pull the bytes from the HTTP response. To do that, we must pass a
deserializeJson(), by calling
http.getStream() instead of
http.getString(). Unfortunately, we now bypass the code that handles chunked transfer encoding, so we must switch to HTTP version 1.0.
HTTPClient http; // Send request http.useHTTP10(true); http.begin("http://arduinojson.org/example.json"); http.GET(); // Parse response DynamicJsonDocument doc(2048); deserializeJson(doc, http.getStream()); // Read values Serial.println(doc["time"].as<long>()); // Disconnect http.end();
Remember to call
useHTTP10(true) when you use
Notice that I used a
DynamicJsonDocument here because the document is quite large. Feel free to use a
StaticJsonDocument if your document is smaller. As always, use the ArduinoJson Assistant to compute the right capacity for your project.
How to send a JSON document in an HTTP request?
Unfortunately, there is no way to use the same trick as above, so we have to use a temporary buffer. Here is how we can do so with a
// Prepare JSON document DynamicJsonDocument doc(2048); doc["hello"] = "world"; // Serialize JSON document String json; serializeJson(doc, json); HTTPClient http; // Send request http.begin("http://httpbin.org/post"); http.POST(json); // Read response Serial.print(http.getString()); // Disconnect http.end();
If you run this program, you’ll see that it prints information on the HTTP requests. That’s the response returned by httpbin.org; it’s very handy to debug your programs.
BONUS: How to see the document when I use a
As we saw, it’s more efficient to pass the
deserializeJson() because it saves a large amount of memory. However, we cannot directly print the content of the
Stream to see what was sent to ArduinoJson.
To see the content that is received from the HTTP response, we can use the
ReadLoggingStream from the StreamUtils library.
ReadLoggingStream loggingStream(http.getStream(), Serial); deserializeJson(doc, loggingStream);
ReadLoggingStream will forward everything to
deserializeJson() and will print the content to the serial port.
- The GitHub example in chapter 3 of Mastering ArduinoJson