JsonHttpClient.ino 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2017
  3. // MIT License
  4. //
  5. // Example of an HTTP client parsing a JSON response.
  6. //
  7. // This program perform an HTTP GET of arduinojson.org/example.json
  8. // Here is the expected response:
  9. // {
  10. // "sensor": "gps",
  11. // "time": 1351824120,
  12. // "data": [
  13. // 48.756080,
  14. // 2.302038
  15. // ]
  16. // }
  17. // See http://arduinojson.org/assistant/ to compute the size of the buffer.
  18. //
  19. // Disclaimer: the code emphasize the communication between client and server,
  20. // it doesn't claim to be a reference of good coding practices.
  21. #include <ArduinoJson.h>
  22. #include <Ethernet.h>
  23. #include <SPI.h>
  24. void setup() {
  25. Serial.begin(9600);
  26. while (!Serial);
  27. echo("Initialize Ethernet library");
  28. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  29. Ethernet.begin(mac) || die("Failed to configure Ethernet");
  30. delay(1000);
  31. echo("Connect to HTTP server");
  32. EthernetClient client;
  33. client.setTimeout(10000);
  34. client.connect("arduinojson.org", 80) || die("Connection failed");
  35. echo("Send HTTP request");
  36. client.println("GET /example.json HTTP/1.0");
  37. client.println("Host: arduinojson.org");
  38. client.println("Connection: close");
  39. client.println() || die("Failed to send request");
  40. echo("Check HTTP status");
  41. char status[32] = {0};
  42. client.readBytesUntil('\r', status, sizeof(status));
  43. if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
  44. echo(status);
  45. die("Unexpected HTTP response");
  46. }
  47. echo("Skip HTTP headers");
  48. char endOfHeaders[] = "\r\n\r\n";
  49. client.find(endOfHeaders) || die("Invalid response");
  50. echo("Allocate JsonBuffer");
  51. const size_t BUFFER_SIZE = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  52. DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);
  53. echo("Parse JSON object");
  54. JsonObject& root = jsonBuffer.parseObject(client);
  55. if (!root.success()) die("Parsing failed!");
  56. echo("Extract values");
  57. echo(root["sensor"].as<char*>());
  58. echo(root["time"].as<char*>());
  59. echo(root["data"][0].as<char*>());
  60. echo(root["data"][1].as<char*>());
  61. echo("Disconnect");
  62. client.stop();
  63. }
  64. void loop() {}
  65. void echo(const char* message) {
  66. Serial.println(message);
  67. }
  68. bool die(const char* message) {
  69. Serial.println(message);
  70. while (true); // loop forever
  71. return false;
  72. }