Sub topic 8
Reading and parsing the response
This chapter assumes that you can connect your Arduino to Wi-Fi and open a TCP connection to a server. It also assumes that you know that HTTP uses requests and responses, and that a response contains a status line, headers, and a body.
An HTTP response is text sent by the server. The parts are separated by a blank line:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1256
Connection: close
<html>...</html>The status line tells you whether the request succeeded. Headers describe the body and the connection. The body contains the requested data.
Read the response in sections
Read the response in this order:
- Read the first line and extract the status code.
- Read headers until you reach an empty line.
- Read the body according to the headers and connection behavior.
The status code is a three-digit number. Codes from 200 through 299 usually mean success. A 404 means the resource was not found. A 500 means the server reported an error. Do not treat every response as successful just because the TCP connection opened.
A header has a name, a colon, and a value. For example, Content-Length: 1256 says that the body contains 1,256 bytes. Content-Type tells you how to interpret those bytes.
Parse a response with WiFiClient
This sketch connects to example.com, sends a GET request, parses the status code and selected headers, then prints the body. The example uses Connection: close, so the server signals the end of the body by closing the connection.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiClient client;
const char host[] = "example.com";
String readLine() {
String line = client.readStringUntil('\n');
line.trim();
return line;
}
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
Serial.println("Waiting for Wi-Fi");
delay(5000);
}
if (!client.connect(host, 80)) {
Serial.println("TCP connection failed");
return;
}
client.println("GET / HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Connection: close");
client.println();
unsigned long start = millis();
while (!client.available() && client.connected()) {
if (millis() - start > 10000) {
Serial.println("Response timeout");
client.stop();
return;
}
delay(10);
}
String statusLine = readLine();
Serial.print("Status: ");
Serial.println(statusLine);
int firstSpace = statusLine.indexOf(' ');
int statusCode = -1;
if (firstSpace >= 0) {
statusCode = statusLine.substring(firstSpace + 1).toInt();
}
Serial.print("Status code: ");
Serial.println(statusCode);
long contentLength = -1;
String contentType = "";
while (client.connected() || client.available()) {
String header = readLine();
if (header.length() == 0) {
break;
}
if (header.startsWith("Content-Length:")) {
contentLength = header.substring(15).toInt();
} else if (header.startsWith("Content-Type:")) {
contentType = header.substring(13);
}
}
Serial.print("Content type: ");
Serial.println(contentType);
Serial.print("Content length: ");
Serial.println(contentLength);
Serial.println("Body:");
while (client.connected() || client.available()) {
if (client.available()) {
Serial.write(client.read());
} else {
delay(1);
}
}
client.stop();
}
void loop() {}readStringUntil('\n') waits for a newline. Calling trim() removes the newline and extra spaces, which makes comparisons easier. The blank line after the headers becomes an empty string, so the loop knows when the body starts.
Common parsing errors
- Reading the body before consuming all headers. The first body bytes can then be mistaken for headers.
- Assuming that every body ends when the connection closes. Some responses use
Content-Lengthor chunked transfer encoding. - Storing a large response in one
String. Small boards have limited RAM, and repeatedStringchanges can fragment memory. - Ignoring the status code. A server can return an error page with valid HTTP syntax.
- Comparing headers with exact capitalization. Header names are case-insensitive, so production code should normalize names or compare them without case sensitivity.
For larger responses, process data as it arrives. For JSON, read only the fields your application needs with a streaming parser instead of copying the entire response into memory.
Exercise
Why must the sketch read the blank line between the headers and the body?
Show answer
The blank line marks the end of the header section. Without reading it, the sketch cannot reliably tell where the body begins.