Sub topic 8
Reading and parsing the response
Sending a request is half of an HTTP exchange. The other half is reading what comes back, and on a small board that needs more care than on a PC. RAM is limited, data arrives in pieces, and servers may answer in ways you did not expect. This chapter shows how to split a response into its parts, check that it succeeded, and extract the values you need without running out of memory.
Prerequisites
This chapter assumes you have already done the following:
- Connected a WiFiNINA board to a network and checked its status.
- Sent an HTTP GET request with
WiFiClientorWiFiSSLClient. - Used
Serialoutput and themillis()timing pattern. - Installed a library from the Library Manager.
Anatomy of a response
An HTTP response is plain text with a fixed layout. The server sends a status line, then header lines, then one empty line, then the body.
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 41
{"city":"Oslo","temp":4.5,"humidity":81}Each line ends with the two characters \r\n (carriage return and line feed). The empty line (just \r\n) is the signal that the headers are finished. Everything after it is the body.
| Part | Example | What you do with it |
|---|---|---|
| Status line | `HTTP/1.1 200 OK` | Read the three-digit status code and decide whether to continue |
| Headers | `Content-Length: 41` | Learn the body size, type, and encoding |
| Blank line | `\r\n` | Marks where the body starts |
| Body | `{"temp":4.5}` | Parse the data you asked for |
Reading the status line and headers
The client object is a Stream, the same Arduino base class that Serial uses. That gives you readStringUntil(), find(), readBytes(), parseInt(), and setTimeout().
Set a timeout first. Without one, the default of one second may be too short for a slow server, and a missing timeout in your own loop can hang the sketch forever.
The next sketch requests a page and prints the status code, the Content-Length header if present, and the start of the body. It sends HTTP/1.0 on purpose. An HTTP/1.0 request tells the server not to use chunked transfer encoding (covered below), so the body arrives as plain bytes.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiClient client;
const char host[] = "example.com";
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
client.setTimeout(5000);
if (!client.connect(host, 80)) {
Serial.println("Connection to server failed");
return;
}
client.println("GET / HTTP/1.0");
client.print("Host: ");
client.println(host);
client.println("Connection: close");
client.println();
// Status line, for example "HTTP/1.0 200 OK"
String statusLine = client.readStringUntil('\n');
statusLine.trim();
int firstSpace = statusLine.indexOf(' ');
int code = statusLine.substring(firstSpace + 1, firstSpace + 4).toInt();
Serial.print("Status code: ");
Serial.println(code);
// Headers, one per line, until the blank line
long contentLength = -1;
while (true) {
String line = client.readStringUntil('\n');
line.trim();
if (line.length() == 0) break; // blank line, or a timeout
line.toLowerCase();
if (line.startsWith("content-length:")) {
contentLength = line.substring(15).toInt();
}
}
Serial.print("Content-Length: ");
Serial.println(contentLength);
// Body, copied into a fixed buffer
char body[129];
size_t wanted = sizeof(body) - 1;
if (contentLength >= 0 && (size_t)contentLength < wanted) {
wanted = contentLength;
}
size_t got = client.readBytes(body, wanted);
body[got] = '\0';
Serial.println(body);
client.stop();
}
void loop() {}Three details in this code matter:
trim()removes the trailing\r.readStringUntil('\n')stops at the line feed but leaves the carriage return in the string. Comparing against an empty string without trimming never matches.- Header names are case-insensitive. Servers send
Content-Length,content-length, orCONTENT-LENGTH. Lowercase the line before comparing. - A timeout looks like a blank line.
readStringUntil()returns an empty string when it times out, so the header loop above also ends on a timeout. The body read then returns zero bytes, which you can detect by checkinggot.
Choosing how much body to read
Your sketch needs to know where the body ends. Servers signal this in one of three ways.
| Method | How you recognize it | How to read it |
|---|---|---|
| Content-Length | `Content-Length: 41` header | Read exactly that many bytes |
| Connection close | No length header, request sent `Connection: close` | Read until the client reports disconnected and `available()` is 0 |
| Chunked | `Transfer-Encoding: chunked` header | Decode chunk sizes yourself, or avoid it |
Chunked encoding splits the body into pieces, each preceded by its size in hexadecimal on its own line. If you print a chunked body raw, you will see stray lines such as 1a or 0 mixed into your data. A JSON parser will fail on them.
The simplest way to avoid chunked responses is to send HTTP/1.0 as in the sketch above. If the server insists on chunked data anyway, detect the header and handle it deliberately, or switch to a different endpoint. Writing a chunk decoder on a small board is possible but rarely worth the code.
Parsing JSON with ArduinoJson
Most web APIs return JSON. Hand-parsing it with indexOf() works for one fixed field but breaks as soon as spacing, ordering, or nesting changes. Use the ArduinoJson library (install "ArduinoJson" by Benoit Blanchon from the Library Manager). The examples here use version 7, which has a single JsonDocument type. Version 6 used StaticJsonDocument<N> with a size you chose yourself.
ArduinoJson can read straight from the client stream. It consumes bytes as they arrive, so you do not need a buffer that holds the whole body. A filter goes further and keeps only the fields you name, which matters when an API returns a large document and you want two values.
The sketch below calls a placeholder API over HTTPS. Replace api.example.com and the path with a real endpoint that returns JSON such as {"city":"Oslo","temp":4.5,"humidity":81}.
#include <WiFiNINA.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h"
WiFiSSLClient client;
const char host[] = "api.example.com";
const char path[] = "/v1/weather";
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
client.setTimeout(5000);
if (!client.connect(host, 443)) {
Serial.println("TLS connection failed");
return;
}
client.print("GET ");
client.print(path);
client.println(" HTTP/1.0");
client.print("Host: ");
client.println(host);
client.println("Accept: application/json");
client.println("Connection: close");
client.println();
String statusLine = client.readStringUntil('\n');
if (!statusLine.startsWith("HTTP/1.") || statusLine.indexOf(" 200") < 0) {
Serial.print("Unexpected status: ");
Serial.println(statusLine);
client.stop();
return;
}
// Skip the remaining headers: find() stops after the blank line
if (!client.find("\r\n\r\n")) {
Serial.println("Headers incomplete");
client.stop();
return;
}
JsonDocument filter;
filter["temp"] = true;
filter["city"] = true;
JsonDocument doc;
DeserializationError err =
deserializeJson(doc, client, DeserializationOption::Filter(filter));
client.stop();
if (err) {
Serial.print("JSON error: ");
Serial.println(err.c_str());
return;
}
const char* city = doc["city"] | "unknown";
float temp = doc["temp"] | 0.0f;
Serial.print(city);
Serial.print(": ");
Serial.print(temp);
Serial.println(" C");
}
void loop() {}The | operator supplies a default when a key is missing or has the wrong type, so a changed API produces unknown and 0.0 instead of a crash. When the API's output is large or the JSON is nested, build the filter to match the nesting. For an array of objects, use filter[0]["temp"] = true; to apply the same filter to every element.
Memory and safety limits
Reading a response is where small boards fail in the field, so set limits deliberately:
- Cap the body. If the server returns 200 KB of HTML instead of 200 bytes of JSON, a loop that appends every byte to a
Stringwill exhaust RAM. Read into a fixed buffer, or stop after a maximum count. - Prefer fixed buffers to
Stringin long-running sketches. RepeatedStringconcatenation fragments the heap, and a sketch that runs for days can fail after thousands of requests. - Use filters. A filter shrinks the memory ArduinoJson needs to the size of the fields you keep.
- Handle
deserializeJsonerrors.EmptyInput,IncompleteInput, andInvalidInputusually mean a timeout, a dropped connection, or a body that was not JSON at all, such as an HTML error page.
Status codes that need a decision
Do not treat every reply as data. Decide what each class of code means for your sketch.
| Code | Meaning | Typical response |
|---|---|---|
| 200 | OK, body follows | Parse the body |
| 204 | Success, no body | Do not try to parse; there is nothing to read |
| 301, 302 | Redirect to the `Location` header | Read the header and request the new URL, or fix the URL in your sketch |
| 401, 403 | Authentication or permission problem | Check your API key; retrying will not help |
| 404 | Wrong path | Fix the path |
| 429 | Too many requests | Wait longer between requests |
| 5xx | Server problem | Retry later with a longer delay |
A redirect from http:// to https:// is common. If your plain HTTP request on port 80 returns 301, switch to WiFiSSLClient and port 443 rather than following the redirect in code.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| `InvalidInput` from `deserializeJson` | Body contains chunk-size lines or HTML | Request `HTTP/1.0`, check the status code, print the raw body |
| `IncompleteInput` | Timeout or early disconnect | Raise `setTimeout()`, check Wi-Fi signal |
| Header loop ends immediately | Timeout returned an empty string, or `\r` not trimmed | Call `trim()`, check the connection before reading |
| Values are `0` or `unknown` | Key names differ from the API | Print the raw JSON and compare key names |
| Sketch resets after a few requests | RAM exhausted by large bodies or `String` growth | Use a fixed buffer and a filter |
Exercise
Your sketch prints a body that begins with a line containing 1f and ends with a line containing 0, and deserializeJson returns InvalidInput. What is happening, and what is the simplest change to your request?
Show answer
The server is using chunked transfer encoding. The 1f and 0 lines are hexadecimal chunk sizes, not part of the JSON. The simplest fix is to send the request as HTTP/1.0 instead of HTTP/1.1, which tells the server not to chunk the body.
Exercise
Extend the ArduinoJson sketch so that a 204 status prints "No content" and a 301 status prints the Location header value, instead of treating both as errors. Which method skips non-matching header lines while you look for Location?
Show answer
Read the status code first. For 204, print "No content" and call client.stop() without parsing. For 301, loop with readStringUntil('\n'), trim() each line, and stop at the blank line. When a line starts with Location: (compared case-insensitively), print the text after the colon. Reading headers line by line with readStringUntil('\n') skips the non-matching lines, because each call consumes one header line.