Sub topic 6
Making an HTTP request
This chapter assumes your board already joins your Wi-Fi network and reports an IP address. It also assumes you are comfortable with Serial output and with the millis() timing pattern. The sketches use the WiFiNINA library (MKR WiFi 1010, Nano 33 IoT) and the arduino_secrets.h file from the credentials chapter.
The working model
HTTP is a text protocol that runs on top of a TCP connection. The board acts as the client. It does four things:
- Resolves a host name to an IP address (DNS).
- Opens a TCP connection to that address, normally on port 80.
- Writes a request as lines of text.
- Reads the response until the server closes the connection.
WiFiClient handles the first two steps inside connect(). It then behaves like Serial: you print() to send and read() to receive.
Anatomy of a request
A minimal HTTP/1.1 request has three parts:
- A request line: the method, the path, and the version, such as
GET / HTTP/1.1. - Header lines, each in the form
Name: value. - One empty line that marks the end of the headers.
HTTP/1.1 requires the Host header. One server often hosts many sites on one IP address, and Host tells it which site you want. Connection: close asks the server to close the connection after it responds. That makes the end of the response easy to detect.
Lines end with carriage return and line feed (\r\n). println() sends exactly that pair, so it is the right call for each line.
The first request
This sketch sends the request and prints the raw response.
#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);
}
if (client.connect(host, 80)) {
client.println("GET / HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Connection: close");
client.println();
} else {
Serial.println("Connection to server failed");
}
}
void loop() {
while (client.available()) {
Serial.write(client.read());
}
if (!client.connected()) {
client.stop();
while (true) {}
}
}Open the Serial Monitor at 115200 baud. You should see a status line (HTTP/1.1 200 OK), a block of headers, a blank line, and then the HTML page.
Three parts of the sketch matter:
client.connect(host, 80)returns 1 on success and 0 on failure. A failure can mean DNS failed, the server is unreachable, or the port is closed. The return value does not say which.client.available()returns how many bytes are waiting in the receive buffer.read()takes one byte at a time, andSerial.write()forwards it unchanged.client.connected()stays true while data is still buffered, even after the server has closed. In this sketch theavailable()loop runs first, so the buffer drains before the board stops the client. Callclient.stop()once you finish, so the module frees its socket. WiFiNINA has only a few sockets, usually four.
What a response looks like
The response has the same layout as the request. Here is a typical response:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1256
<!doctype html>...The first line is the status line. Its three-digit code tells you what happened.
| Code range | Meaning | Examples |
|---|---|---|
| 2xx | Success | 200 OK |
| 3xx | Redirect: look elsewhere | 301 Moved Permanently, 302 Found |
| 4xx | Your request was wrong | 400 Bad Request, 404 Not Found |
| 5xx | The server failed | 500 Internal Server Error |
A 301 or 302 response with a Location header is common on port 80 when a site wants you to use HTTPS. The board does not follow redirects on its own. Your code has to read the new location and repeat the request, or you can request the HTTPS URL directly (see the HTTPS chapter).
Checking the status and skipping headers
Printing everything is fine for exploring. Real programs need the status code and the body without the headers. This sketch does both. It uses fixed-size buffers instead of String to avoid heap fragmentation on boards with limited RAM.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiClient client;
const char host[] = "example.com";
const unsigned long RESPONSE_TIMEOUT_MS = 10000;
bool waitForData() {
unsigned long start = millis();
while (!client.available()) {
if (!client.connected() || millis() - start > RESPONSE_TIMEOUT_MS) {
return false;
}
}
return true;
}
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
if (!client.connect(host, 80)) {
Serial.println("Connection to server failed");
return;
}
client.println("GET / HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Connection: close");
client.println();
if (!waitForData()) {
Serial.println("No response");
client.stop();
return;
}
char line[128];
int n = client.readBytesUntil('\n', line, sizeof(line) - 1);
line[n] = '\0';
if (strncmp(line, "HTTP/1.", 7) != 0) {
Serial.println("Not an HTTP response");
client.stop();
return;
}
int code = atoi(line + 9);
Serial.print("Status code: ");
Serial.println(code);
// Skip headers: they end at an empty line (just "\r").
while (true) {
n = client.readBytesUntil('\n', line, sizeof(line) - 1);
if (n == 0 || (n == 1 && line[0] == '\r')) break;
}
// Everything left is the body.
while (client.connected() || client.available()) {
if (client.available()) {
Serial.write(client.read());
}
}
client.stop();
}
void loop() {}How it works:
waitForData()gives the server up to ten seconds to start answering. Without a limit, a stalled server would freeze the sketch forever.readBytesUntil('\n', ...)reads up to the newline or until the stream timeout (one second by default). It returns 0 on a timeout, so the header loop also ends if the connection stalls.- The status code starts at character 9 of
HTTP/1.1 200 OK, soatoi(line + 9)converts it to an integer. - The body loop ends only when the connection has closed and the buffer is empty.
Sending data to a server
Request methods other than GET need a body. For a POST, add a Content-Length header with the exact byte count of the body, then the blank line, then the body:
const char body[] = "temp=21.5";
client.println("POST /log HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(strlen(body));
client.println("Connection: close");
client.println();
client.print(body);If Content-Length is smaller than the body, the server cuts the body off. If it is larger, the server waits for bytes that never arrive, and eventually times out.
Edge cases and common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `connect()` returns 0 | DNS failure, wrong host, wrong port, no Wi-Fi | Check `WiFi.status()`, try the server's IP address to rule out DNS |
| 400 Bad Request | Missing `Host` header or missing blank line | Send `Host` and end the headers with an empty `println()` |
| Nothing printed, sketch hangs | No timeout, server never answers | Use a deadline such as `waitForData()` |
| Body contains numbers like `4e2` between chunks | Server used chunked transfer encoding | See below |
| Response is a 301 or 302 | Server redirects, often to HTTPS | Use the HTTPS client on port 443 |
| Works once, then fails | Client never stopped, sockets exhausted | Call `client.stop()` after each request |
| Garbled or truncated output | Reading too slowly, buffer overflow | Read in a tight loop, avoid long `delay()` calls |
Chunked transfer encoding. With HTTP/1.1, a server may send the body in chunks and omit Content-Length. Each chunk begins with its size in hexadecimal on its own line, and the body ends with a chunk of size 0. If you see stray hex numbers in your output, this is why. You can ask for a simpler response by using HTTP/1.0 (GET / HTTP/1.0), which servers rarely chunk, but then you lose the Host requirement and some virtual-hosted sites will not respond correctly. Many APIs also let you request a compact JSON reply, which is usually small enough that chunking does not matter.
Blocking behavior. connect() can block for several seconds when a server is unreachable. During that time your loop() does nothing else. Keep this in mind if the board is also reading sensors or driving outputs. The reconnection chapter covers how to structure sketches around this.
Request rate. Public servers rate-limit or ban clients that send many requests. Space requests out with a millis() check, for example one request every 60 seconds or more, and always honor the limits a service documents.
Exercise
A request you send to a web server returns "400 Bad Request". Your sketch sends GET / HTTP/1.1, then Connection: close, then an empty line. What is missing, and why does the server reject the request?
Show answer
The Host header is missing. HTTP/1.1 requires it, because one server can host many sites on a single IP address and uses Host to choose the right one. Add client.print("Host: "); client.println(host); before the empty line.
Exercise
In the status-and-body sketch, why does the final loop test client.connected() || client.available() instead of only client.connected()?
Show answer
The server may close the connection while bytes are still waiting in the receive buffer. connected() can then return false although unread data remains. Testing available() as well keeps the loop running until the buffer is empty, so the end of the body is not lost.
Exercise
You want to send the body value=42 with a POST. What value must Content-Length have, and what happens if you set it to 3?
Show answer
It must be 8, the number of bytes in value=42. With 3, the server reads only val and ignores or rejects the rest, so your data is truncated or the request fails.