0
0
Arduinoprogramming~7 mins

HTTP requests from Arduino

Choose your learning style9 modes available
Introduction

HTTP requests let your Arduino talk to websites or online services. This helps your Arduino send or get data from the internet.

You want to send sensor data from Arduino to a web server.
You want to get weather info from an online API to display on Arduino.
You want to control Arduino remotely using commands from a website.
You want to log Arduino data online for later review.
Syntax
Arduino
WiFiClient client;
HTTPClient http;

http.begin(client, "http://example.com/data");
int httpCode = http.GET();
if (httpCode > 0) {
  String payload = http.getString();
  // use payload
}
http.end();

Use WiFiClient to create a network connection.

HTTPClient helps send GET or POST requests easily.

Examples
This example sends a GET request and prints the response.
Arduino
WiFiClient client;
HTTPClient http;

http.begin(client, "http://example.com");
int code = http.GET();
if (code > 0) {
  String response = http.getString();
  Serial.println(response);
}
http.end();
This example sends a POST request with JSON data.
Arduino
WiFiClient client;
HTTPClient http;

http.begin(client, "http://example.com/post");
http.addHeader("Content-Type", "application/json");
int code = http.POST("{\"temp\":25}");
if (code > 0) {
  String response = http.getString();
  Serial.println(response);
}
http.end();
Sample Program

This program connects to WiFi, sends a GET request to get current UTC time from an API, and prints the response.

Arduino
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");

  WiFiClient client;
  HTTPClient http;

  http.begin(client, "http://worldtimeapi.org/api/timezone/Etc/UTC");
  int httpCode = http.GET();

  if (httpCode > 0) {
    String payload = http.getString();
    Serial.println("Response:");
    Serial.println(payload);
  } else {
    Serial.println("Error on HTTP request");
  }
  http.end();
}

void loop() {
  // nothing here
}
OutputSuccess
Important Notes

Make sure your Arduino board supports WiFi (like ESP32 or ESP8266).

Replace your_SSID and your_PASSWORD with your WiFi details.

Use Serial Monitor to see printed messages and responses.

Summary

HTTP requests let Arduino communicate with web services.

Use WiFiClient and HTTPClient libraries for easy HTTP calls.

GET requests fetch data; POST requests send data.