When running the code I receive the following error
Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
D:DataDocsArduinoCryptoTickerCryptoTicker.ino: In function 'void loop()':
CryptoTicker:71:15: error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
71 | http.begin(url);
| ~~~~~~~~~~^~~~~
CryptoTicker:105:17: error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
105 | http.begin(historyURL);
| ~~~~~~~~~~^~~~~~~~~~~~
exit status 1
call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
I can confirm I have correctly installed the ESP8266 library
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
Hi,
i have a problem in :
//Hier wird der Wert an die Smarthome-Umgebung übertragen
if (sender.begin(“http://makesmart-server:51828/?accessoryId=temperatur&value=” + String(temperature))){
i recive this message
call to ‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
can somebody help mi, thanks
Renato
It seems that you have to pass in your wifiClient like:
if (sender.begin(wifiClient, "http://makesmart-server:51828/?accessoryId=temperatur&value=" + String(temperature))){
// ...
}
Maybe there was an update in the library or the issue is somewhere else.
Could you share your whole code?
Thanks very much, but there is another problem in the same line:
//Hier wird der Wert an die Smarthome-Umgebung übertragen
if (sender.begin(wifiClient, “http://makesmart-server:51828/?accessoryId=temperatur&value=” + String(temperature))){
now receive this message:
extended character “ is not valid in an identifier
@renato Because these “ are not double quotes. Use «.
Share your whole code that we can see how your client is named.
Yes thank you, I had thought this and I corrected the error but I had not seen that before ‘http’ there was another wrong double quotes.
unfortunately there is another problem
// Wenn alles abgeschlossen ist, wird die Verbindung wieder beendet
sender.end();
}else {
I receive this message:
expected unqualified-id before ‘else’
…without you I would not be able to compile this sketch
Share your whole code! And please use code tags if you post.
Hi
I took the complete sketch from this page,
https://makesmart.net/homekit-thermometer-diy-esp8266-d1-mini/#Einbidung-in-das-Smarthome-Homebridge
WLAN TERMOMETER GET-Request
GET-Request an einen HTTP-Server
Created by cooper, 2020
but when I load it on Arduino IDE and I do a verification I get many mistakes and I am not capable of correcting them, unfortunately I know little Java language, I am starting now, I have little experience, sorry . I copy sketches that are useful and I use them, everything is fine, sometimes not. This sketch is good for me
Thank you
@renato I tested it right now. Copied the code 1:1 — it works. So maybe you have some mistakes in our own code. Share the while thing otherwise nobody can help you.
Let’s start with order
first I copied the sketches from the page:
https://makesmart.net/homekit-thermometer-diy-esp8266-d1-mini/
/*
WLAN TERMOMETER GET-Request
GET-Request an einen HTTP-Server
Created by cooper, 2020
makesmart.net
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
HTTPClient sender;
// WLAN-Daten
const char* ssid = "WLAN_SSID";
const char* password = "WLAN_PASSWD";
//Messintervall in Sekunden
int wait = 5;
//Temperatur
float temperature;
void push(){
//Hier wird der Wert an die Smarthome-Umgebung übertragen
if (sender.begin("http://makesmart-server:51828/?accessoryId=temperatur&value=" + String(temperature))){
// HTTP-Code der Response speichern
int httpCode = sender.GET();
if (httpCode > 0) {
// Anfrage wurde gesendet und Server hat geantwortet
// Info: Der HTTP-Code für 'OK' ist 200
if (httpCode == HTTP_CODE_OK) {
// Hier wurden die Daten vom Server empfangen
// String vom Webseiteninhalt speichern
String payload = sender.getString();
// Hier kann mit dem Wert weitergearbeitet werden
// ist aber nicht unbedingt notwendig
Serial.println(payload);
}
}else{
// Falls HTTP-Error
Serial.printf("HTTP-Error: ", sender.errorToString(httpCode).c_str());
}
// Wenn alles abgeschlossen ist, wird die Verbindung wieder beendet
sender.end();
}else {
Serial.printf("HTTP-Verbindung konnte nicht hergestellt werden!");
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
Serial.println("Verbunden!");
wait = wait * 1000;
sensors.begin();
}
void loop() {
sensors.requestTemperatures();
Serial.print(sensors.getTempCByIndex(0));
Serial.println(" °C");
temperature = sensors.getTempCByIndex(0);
push();
delay(wait);
}
At the line 34
if (sender.begin("http://makesmart-server:51828/?accessoryId=temperatur&value=" + String(temperature))){
ArduinoINO reports an error
‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
So I added (line 13)
#include <WiFiClient.h>
and edited ex line 34 now line 35, this is the whole schetch:
/*
WLAN TERMOMETER GET-Request
GET-Request an einen HTTP-Server
Created by cooper, 2020
makesmart.net
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
#include <WiFiClient.h>
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
HTTPClient sender;
// WLAN-Daten
const char* ssid = "WLAN_SSID";
const char* password = "WLAN_PASSWD";
//Messintervall in Sekunden
int wait = 5;
//Temperatur
float temperature;
void push(){
//Hier wird der Wert an die Smarthome-Umgebung übertragen
if (sender.begin(WiFiClient, "http://makesmart-server:51828/?accessoryId=temperatur&value=" + String(temperature))){
// HTTP-Code der Response speichern
int httpCode = sender.GET();
if (httpCode > 0) {
// Anfrage wurde gesendet und Server hat geantwortet
// Info: Der HTTP-Code für 'OK' ist 200
if (httpCode == HTTP_CODE_OK) {
// Hier wurden die Daten vom Server empfangen
// String vom Webseiteninhalt speichern
String payload = sender.getString();
// Hier kann mit dem Wert weitergearbeitet werden
// ist aber nicht unbedingt notwendig
Serial.println(payload);
}
}else{
// Falls HTTP-Error
Serial.printf("HTTP-Error: ", sender.errorToString(httpCode).c_str());
}
// Wenn alles abgeschlossen ist, wird die Verbindung wieder beendet
sender.end();
}else {
Serial.printf("HTTP-Verbindung konnte nicht hergestellt werden!");
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
Serial.println("Verbunden!");
wait = wait * 1000;
sensors.begin();
}
void loop() {
sensors.requestTemperatures();
Serial.print(sensors.getTempCByIndex(0));
Serial.println(" °C");
temperature = sensors.getTempCByIndex(0);
push();
delay(wait);
}
Now at the line 35 Arduino report:
expected primary-expression before ‘,’ token
help me thanks
Which board do you use?
As I said before. I copied the code and it works for me.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
#include <WiFiClient.h>
You already have a WiFi Client
imported: #include <ESP8266WiFi.h>
.
Maybe you can tell which board do you use and which version of libraries / arduino ide.
This sketch is meant to be for ESP8266 boards.
I use a
WeMos D1 Mini ESP8266 ESP-12F
But I have the report
“expected primary-expression before ‘,’ token”
During the check
I also deleted
#include <WiFiClient.h>
Which Arduino / ESP Version do you use?
For me it’s:
Arduino IDE: 1.8.13
ESP8266: 2.7.4
You can find ESP8266 Boardversion under Tools -> Board -> Boards manager -> Search for ESP8266
Maybe there was an update or you are outdated.
For me ArduinoIDE 1.8.15
ESP8266 board: 3.0.0
I tried
LOLIN (WEMOS) D1 mini(clone) — Generic EPS 8266 Module — NodeMCU 1.0 (ESP 12E Module)
but I have always had the same result
Now I download Arduino IDE: 1.8.13 and I try
I trie: nothing has changed (unfortunately)
@renato try to use older esp Version. Arduino IDE Version shouldn’t matter here I think.
ESP8266 Version 2.7.4 as cooper said. Maybe you can try this?
Good idea but it is not possible, now I use Arduino IDE: 1.8.13 but the possible choice of ESP8266 Version is only the version.3.0.0, previously I renamed tho old folder “Arduino” that of the precedent Arduino IDE 1.8.15installed, so that Arduino IDE: 1.8.13 shuld have it own folder, without interference
I managed to set ESP8266 Version 2.7.4, (still little beginner’s practice), set IP address, installed plugin, changed config.json, now everything works. Thank you all
Loading
Содержание
- Call to httpclient begin declared with attribute error obsolete api use begin wificlient url
- Ähnliche Themen
- Call to httpclient begin declared with attribute error obsolete api use begin wificlient url
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: [SOLVED] mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: [SOLVED] mega-20210503 doesn’t compile on Arduino 1.8.15
- Re: mega-20210503 doesn’t compile on Arduino 1.8.15
- ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE (JSON, URL Encoded, Text)
- HTTP Request Methods: GET vs POST
- HTTP GET
- HTTP POST
- HTTP GET/POST with ESP8266
- Prerequisites
- Arduino IDE
- Arduino_JSON Library
- Parts Required
- Preparing Node-RED (optional)
- Other Web Services or APIs
- 1. ESP8266 HTTP GET: Value or Query in URL
- Code ESP8266 HTTP GET with Arduino IDE
- Setting your network credentials
- Setting your serverName
- HTTP GET Request
- Demonstration
- 2. ESP8266 HTTP GET: JSON Data Object or Plain Text
- Setting your serverName
- HTTP GET Request (JSON Object)
- Decoding JSON Object
- HTTP GET Demonstration
- 3. ESP8266 HTTP POST: URL Encoded, JSON Data Object, Plain Text
- Setting your serverName
- HTTP POST URL Encoded
- HTTP POST JSON Object
- HTTP Plain Text
- HTTP POST Demonstration
- Wrapping Up
- [eBook] Build Web Servers with ESP32 and ESP8266 (2nd Edition)
- Recommended Resources
- What to Read Next…
- ESP8266 Web Server with Arduino IDE
- ESP8266 NodeMCU with TDS Sensor (Water Quality Sensor)
- VS Code Workspaces with ESP32 and ESP8266 Projects
- Enjoyed this project? Stay updated by subscribing our newsletter!
- 22 thoughts on “ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE (JSON, URL Encoded, Text)”
Call to httpclient begin declared with attribute error obsolete api use begin wificlient url
Hi,
i have a problem in :
//Hier wird der Wert an die Smarthome-Umgebung übertragen
if (sender.begin(“http://makesmart-server:51828/?accessoryId=temperatur&value=” + String(temperature)))<
i recive this message
call to ‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
can somebody help mi, thanks
Renato
It seems that you have to pass in your wifiClient like:
Maybe there was an update in the library or the issue is somewhere else.
Could you share your whole code?
Thanks very much, but there is another problem in the same line:
//Hier wird der Wert an die Smarthome-Umgebung übertragen
if (sender.begin(wifiClient, “http://makesmart-server:51828/?accessoryId=temperatur&value=” + String(temperature)))<
now receive this message:
extended character “ is not valid in an identifier
@renato Because these “ are not double quotes. Use «.
Share your whole code that we can see how your client is named.
Yes thank you, I had thought this and I corrected the error but I had not seen that before ‘http’ there was another wrong double quotes.
unfortunately there is another problem
// Wenn alles abgeschlossen ist, wird die Verbindung wieder beendet
sender.end();
>else <
I receive this message:
expected unqualified-id before ‘else’
…without you I would not be able to compile this sketch
Share your whole code! And please use code tags if you post.
Hi
I took the complete sketch from this page,
WLAN TERMOMETER GET-Request
GET-Request an einen HTTP-Server
Created by cooper, 2020
but when I load it on Arduino IDE and I do a verification I get many mistakes and I am not capable of correcting them, unfortunately I know little Java language, I am starting now, I have little experience, sorry . I copy sketches that are useful and I use them, everything is fine, sometimes not. This sketch is good for me
Thank you
@renato I tested it right now. Copied the code 1:1 — it works. So maybe you have some mistakes in our own code. Share the while thing otherwise nobody can help you.
Let’s start with order
first I copied the sketches from the page:
ArduinoINO reports an error
‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
So I added (line 13)
and edited ex line 34 now line 35, this is the whole schetch:
Now at the line 35 Arduino report:
expected primary-expression before ‘,’ token
Which board do you use?
As I said before. I copied the code and it works for me.
You already have a WiFi Client imported: #include .
Maybe you can tell which board do you use and which version of libraries / arduino ide.
This sketch is meant to be for ESP8266 boards.
WeMos D1 Mini ESP8266 ESP-12F
But I have the report
“expected primary-expression before ‘,’ token”
During the check
Which Arduino / ESP Version do you use?
For me it’s:
Arduino IDE: 1.8.13
ESP8266: 2.7.4
You can find ESP8266 Boardversion under Tools -> Board -> Boards manager -> Search for ESP8266
Maybe there was an update or you are outdated.
For me ArduinoIDE 1.8.15
ESP8266 board: 3.0.0
LOLIN (WEMOS) D1 mini(clone) — Generic EPS 8266 Module — NodeMCU 1.0 (ESP 12E Module)
but I have always had the same result
Now I download Arduino IDE: 1.8.13 and I try
I trie: nothing has changed (unfortunately)
@renato try to use older esp Version. Arduino IDE Version shouldn’t matter here I think.
ESP8266 Version 2.7.4 as cooper said. Maybe you can try this?
Good idea but it is not possible, now I use Arduino IDE: 1.8.13 but the possible choice of ESP8266 Version is only the version.3.0.0, previously I renamed tho old folder “Arduino” that of the precedent Arduino IDE 1.8.15installed, so that Arduino IDE: 1.8.13 shuld have it own folder, without interference
I managed to set ESP8266 Version 2.7.4, (still little beginner’s practice), set IP address, installed plugin, changed config.json, now everything works. Thank you all
Ähnliche Themen
@cooper Ahhhhhhhhh nein waren sie nicht :schmartie:
Danke vielmals.
@dieterh … Guten Abend … es hat perfekt funktioniert . Echt klasse und lieben Dank für Deine klasse ergänzende Beschreibung. In diesem kleinen Projekt hab ich echt viel gelernt. So das man jetzt alle Möglichkeiten hat mit RedMatic/NideRed über MQTT sich alles anzeigen lassen kann was das Smarte Herz begehrt.
Lieben Dank bis bald Dirk
@intruder Auch wenn es verspätet kommt vielen Dank! Hab den Sketch mal mit deinen Angaben geupdated! 🙂 Danke
Wer sich mit der Arduino IDE und Modulen wie ESP8266, ESP32 oder auch dem Arduino selber beschäftigt, wird früher oder später mal über das Problem stolpern, verschiedene Datentypen zu kombinieren zu wollen, oder auch Datentypen im Allgemeinen umwandeln zu wollen, um die Daten dann in anderen Operationen nutzen zu können. Ein gängiger cast wäre zum Beispiel eine int Variable in eine float Variable umzuwandeln, um damit genauer rechnen zu können.
Leider gib es keine Methode oder Funktion, die universell einsetzbar ist. Es kommt immer ganz drauf an, welchen Datentypen ihr umwandeln wollt, und vor allem welcher Datentyp am Ende rauskommen soll. Hier versuche ich mal alle Gängigen Datentyp-Konvertierungen aufzulisten — gruppiert nach dem gewünschten End-Datentyp.
Habt ihr weitere Vorschläge und Hinweise bzw. Snippets, dann würde ich mich freuen, wenn ihr sie unter diesem Beitrag hier teilen würdet.
Datentyp : String
Integer
int i = 25; String convertedString = String(i); // «25»
Float
float i = 22.5367; String convertedString = String(i, 3); // «22.536»
Bool
String
String number = «255»; int i = number.toInt(); // 255
Float
float number = «123.232»; int i = (int)number; // 123
Char
Int
int i = 187; float myFloat= float(i); // 187.00
Источник
Call to httpclient begin declared with attribute error obsolete api use begin wificlient url
#1 Post by diyprojectz » 01 Aug 2021, 12:35
Followed instructions from:
I just need P065 (DFPLayer Mini) on 1M ESP-01S, no other changes made. Tried Arduino 1.8.13 and 1.8.15, doesn’t compile, produces this error:
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#2 Post by TD-er » 01 Aug 2021, 12:43
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#3 Post by diyprojectz » 01 Aug 2021, 12:53
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#4 Post by TD-er » 01 Aug 2021, 12:59
With context I meant the surrounding lines so I can see where you’re getting the error.
I did compare it with the latest source and I suggest to use the latest source as it is more stable regarding WiFi reconnects.
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#5 Post by diyprojectz » 01 Aug 2021, 13:14
I tried with latest sources from github. I get the following error:
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#6 Post by TD-er » 01 Aug 2021, 13:19
Looks like you’re using esp8266/Arduino core 3.0.x instead of core 2.7.4
Can you please check this?
Also the selected flash layout will give the next build error as we’re never going to fit in 470 kB.
Please select 128k SPIFFS, the rest for sketch size.
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#7 Post by Ath » 01 Aug 2021, 13:36
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#8 Post by diyprojectz » 01 Aug 2021, 13:55
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#9 Post by TD-er » 01 Aug 2021, 14:02
The core 3.0.x is only available since a few weeks now and I do have a pull request pending to be able to use the new core.
The reason I have not yet merged it, is because each build feels somewhat like a hit-or-miss whether it is stable.
Not sure yet what is causing it.
I may have to take another look at the need to alter the execution policy to use PlatformIO/VS code.
I do remember it was needed a long time ago, but I’m not sure anymore why it was needed and thus also not sure if it is still needed.
It is possible it can run without, but makes frequent use a bit tedious as it may not start the Python virtual env automatically. But like I said, I may have to look into it.
This is a bit tricky though, as I may need to run it on a clean Windows install to test it.
Re: [SOLVED] mega-20210503 doesn’t compile on Arduino 1.8.15
#10 Post by diyprojectz » 01 Aug 2021, 14:49
Re: [SOLVED] mega-20210503 doesn’t compile on Arduino 1.8.15
#11 Post by TD-er » 01 Aug 2021, 15:15
Re: mega-20210503 doesn’t compile on Arduino 1.8.15
#12 Post by Ath » 01 Aug 2021, 16:48
Источник
ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE (JSON, URL Encoded, Text)
In this guide, you’ll learn how to make HTTP GET and HTTP POST requests with the ESP8266 NodeMCU board with Arduino IDE. We’ll cover examples on how to get values, post JSON objects, URL encoded requests, and more.
HTTP Request Methods: GET vs POST
The Hypertext Transfer Protocol (HTTP) works as a request-response protocol between a client and server. Here’s an example:
- The ESP8266 (client) submits an HTTP request to a Raspberry Pi running Node-RED (server);
- The server returns a response to the ESP8266 (client);
- Finally, the response contains status information about the request and may also contain the requested content.
HTTP GET
GET is used to request data from a specified resource. It is often used to get values from APIs.
For example, you can have:
Note that the query string (name = temperature and value = value1) is sent in the URL of the HTTP GET request.
Or you can use a simple request to return a value or JSON object, for example:
(With HTTP GET, data is visible to everyone in the URL request.)
HTTP POST
POST is used to send data to a server to create/update a resource. For example, publish sensor readings to a server.
The data sent to the server with POST is stored in the request body of the HTTP request:
In the body request, you can also send a JSON object:
(With HTTP POST, data is not visible in the URL request. However, if it’s not encrypted, it’s still visible in the request body.)
HTTP GET/POST with ESP8266
In this guide, we’ll explore the following scenarios:
Prerequisites
Before proceeding with this tutorial, make sure you complete the following prerequisites.
Arduino IDE
We’ll program the ESP8266 NodeMCU board using Arduino IDE, so make sure you have the ESP8266 add-on installed.
Arduino_JSON Library
You also need to install the Arduino_JSON library. You can install this library in the Arduino IDE Library Manager. Just go to Sketch > Include Library > Manage Libraries and search for the library name as follows:
Parts Required
For this tutorial you need the following parts:
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Preparing Node-RED (optional)
As an example, we’ll create a web service with a Raspberry Pi and Node-RED to act as a web service (like an API). Basically, you’ll make HTTP GET and HTTP POST requests to your Raspberry Pi to get values or update them. You can use any other web service.
If you don’t have Node-RED installed, follow the next tutorials:
Having Node-RED running on your Raspberry Pi, go to your Raspberry Pi IP address followed by :1880.
The Node-RED interface should open. You can simply import the final flow:
Go to Menu > Import and copy the following to your Clipboard to create your Node-RED flow.
Other Web Services or APIs
In this guide, the ESP8266 performs HTTP requests to Node-RED, but you can use these examples with other services like ThingSpeak, IFTTT.com (Web Hooks service), OpenWeatherMap.org, PHP server, etc… All examples presented in this guide will also work with other APIs.
In summary, to make this guide compatible with any service, you need to search for the service API documentation. Then, you need the server name (URL or IP address), and parameters to send in the request (URL path or request body). Finally, modify our examples to integrate with any API you want to use.
1. ESP8266 HTTP GET: Value or Query in URL
In the first example, the ESP8266 will make an HTTP GET request to update a reading in a service. This type of request could also be used to filter a value, request a value or return a JSON object.
Code ESP8266 HTTP GET with Arduino IDE
After installing the necessary board add-ons and libraries, copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.
Setting your network credentials
Modify the next lines with your network credentials: SSID and password. The code is well commented on where you should make the changes.
Setting your serverName
You also need to type your domain name or Node-RED IP address, so the ESP publishes the readings to your own server.
Now, upload the code to your board and it should work straight away.
Read the next section, if you want to learn how to make the HTTP GET request.
HTTP GET Request
In the loop() is where you actually make the HTTP GET request every 5 seconds with sample data:
Note: if Node-RED requires authentication, uncomment the following line and insert the Node-RED username and password.
The ESP8266 makes a new request in the following URL to update the sensor field with a new temperature.
Then, the following lines of code save the HTTP response from the server.
Demonstration
With your board running the new sketch, open the Node-RED debug window. You’ll see that the sample values are being printed successfully (24.37).
2. ESP8266 HTTP GET: JSON Data Object or Plain Text
This next example shows how to make an HTTP GET request to get a JSON object and decode it with the ESP8266. Many APIs return data in JSON format.
Copy the next sketch to your Arduino IDE (type your SSID and password):
Setting your serverName
Enter your domain name or Node-RED IP address, so the ESP requests the sensor readings that will be retrieved in a JSON object.
Now, upload the code to your board.
HTTP GET Request (JSON Object)
In the loop() , call the httpGETRequest() function to make the HTTP GET request:
The httpGETRequest() function makes a request to Node-RED address http://192.168.1.106:1880/get-sensor and it retrieves a string with a JSON object.
Note: if Node-RED requires authentication, uncomment the following line and insert the Node-RED username and password.
Decoding JSON Object
To get access to the values, decode the JSON object and store all values in the sensorReadingsArr array.
HTTP GET Demonstration
After uploading the code, open the Arduino IDE and you’ll see that it’s receiving the following JSON data:
Then, you print the decoded JSON object in the Arduino IDE Serial Monitor.
For debugging purposes, the requested information is also printed in the Node-RED debug window.
3. ESP8266 HTTP POST: URL Encoded, JSON Data Object, Plain Text
Finally, you’ll learn how to make an HTTP POST request with an ESP8266.
With this example, your ESP8266 can make HTTP POST requests using three different types of body requests: URL encoded, JSON object or plain text. These are the most common methods and should integrate with most APIs or web services.
Copy the next sketch to your Arduino IDE (type your SSID and password):
Setting your serverName
Enter your domain name or Node-RED IP address, so the ESP posts sample sensor readings.
Now, upload the code to your board.
HTTP POST URL Encoded
To make an HTTP POST request of type URL encoded, like this
You need to run the following in your Arduino code:
Note: if Node-RED requires authentication, uncomment the following line and insert the Node-RED username and password.
HTTP POST JSON Object
Or if you prefer to make an HTTP POST request with a JSON object:
Use the next snippet:
HTTP Plain Text
If you want to send plain text or a value, use the following:
Note: the Node-RED flow we’re using (web service) is not setup to receive plain text, but if the API that you plan to integrate only accepts plain text or a value, you can use the previous snippet.
HTTP POST Demonstration
In the Node-RED debug window, you can view that your ESP is making an HTTP POST request every 5 seconds.
And in this example, those values are also sent to 3 Gauges and are displayed in Node-RED Dashboard:
Wrapping Up
In this tutorial you’ve learned how to integrate your ESP8266 with online services using HTTP GET and HTTP POST requests.
HTTP GET and HTTP POST are commonly used in most web services and APIs. These can be useful in your projects to: publish your sensor readings to a web service like IFTTT, ThingSpeak; to an ESP8266 or Raspberry Pi web server or to your own server; to request data from the internet or from your database, and much more.
You might also like reading:
I hope you liked this project. If you have any questions, post a comment below and we’ll try to get back to you.
If you like ESP8266, you might consider enrolling in our eBook “Home Automation using ESP8266“. You can also access our free ESP8266 resources here.
Thank you for reading.
[eBook] Build Web Servers with ESP32 and ESP8266 (2nd Edition)
Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »
Recommended Resources
Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.
Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.
Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!
What to Read Next…
ESP8266 Web Server with Arduino IDE
ESP8266 NodeMCU with TDS Sensor (Water Quality Sensor)
VS Code Workspaces with ESP32 and ESP8266 Projects
Enjoyed this project? Stay updated by subscribing our newsletter!
22 thoughts on “ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE (JSON, URL Encoded, Text)”
what sensor are we talking about and what Ip are you talking about ? Does this have to have a node-Red. Do I have to access a web site, my own? I am sorry I usually get your stuff but this is remiss.
Hello John, I apologize for the confusion.
This guide is meant to be used with any service that supports HTTP GET or HTTP POST requests (like IFTTT.com, ThingSpeak.com, etc…).
In this tutorial I’ve used a local installation of Node-RED in a Raspberry Pi (so, in the ServerName you should type your RPi IP address for Node-RED or modify it to work with any service that you desire).
The “sensor” is just dummy data to be used as an example. The ESP is not reading any sensor, instead it’s sending sample values to Node-RED or to requesting them.
Regards,
Rui
Hi, I hope you are well,
Do you have an example of php, that recib this json?
Please!
Thanks.
It would be nice to see some simple examples of the web server side using php to reply to a request that works with each option.
Never mind. Google is my friend! 🙂
Does anyone know how I can solve this problem?
‘JSONVar’ was not declared in this scope
JSONVar myObject = JSON.parse(sensorReadings);
Hi.
You need to install the Arduino_JSON Library with the “_” on the name.
Regards,
Sara
Can we do it ESP8266 ESP-01?
Hi Rui and Sara,
Thanks for ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE project.
I am getting following error when doing verify/compile with ESP8266,
call to ‘HTTPClient::begin’ declared with attribute error: obsolete API, use ::begin(WiFiClient, url).
On at line http.begin(serverName);
I have the same problem and have no idea what to do with it. Can you help us, Rui and Sara?
Thanks for sharing the solution.
We’ll have to update all the tutorials that use that method soon.
Regards,
Sara
you have to pass the instance of WiFiclient with the url in the argument of http.begin().
example:
WiFiClient client; // client is the instance of WifiClient;
http.begin(client,url);
float sensorReadingsArr[3];
sensorReadingsArr[i] = double(value);
Hi, I want to ask. How if I want the data “sensorReadingsArr” only number not float? What code I should use?
Like this maybe?
int sensorReadingsArr[3];
sensorReadingsArr[i] = value;
hi
I have problem with http.getstring(), I’m trying to fetch json data from php file it work’s fine but when connect esp8266 to some specific network this function get weird characters like this:
Fr⸮99⸮⸮⸮b8h0ԑ⸮⸮⸮⸮ ⸮⸮pP⸮cgF⸮⸮m5⸮⸮g1⸮b⸮?qu⸮⸮B⸮⸮T⸮⸮ ⸮`
and actual data should like this:
<“mac”:”EC:FA:BC:DD:2F:3E”,”burner1″:”0000000″,”info”:”1000010″,…>
any idea how to solve this?
thank you
Hello Rui and Sara,
I’m trying to send data to my own webserver (apache2 on Raspi4). The esp connects well, but answer is 401. So I need to include username/password in my POST request. But how? Can you give me a short description or code snippet how to do this in the above script?
Thank you.
Hi Rui! Hi Sara! Very insightful projects! Thank you very much!
Would be possible to POST a JSON Object but connecting via 2G instead of WiFi?
Guau! Thank you Sara for your answer!
I have implemented your code with small adjustment, basically the content type to json, to my application as follows:
client.print(String(“POST “) + resource + ” HTTP/1.1rn”);
client.print(String(“Host: “) + server + “rn”);
client.println(“Connection: close”);
client.println(“Content-Type: application/json”);
client.print(“Content-Length: “);
client.println(httpRequestData.length());
client.println();
client.println(httpRequestData);
unsigned long timeout = millis();
while (client.connected() && millis() — timeout
// Close client and disconnect
client.stop();
SerialMon.println(F(«Server disconnected»));
But the response I got reading the serial shows I am basically reading what was already transmitted to the server when I was connecting via WiFi. The new data doesn’t show up at the server. Seems like I am getting info from the server instead of posting!? Can you spot some gross mistake from my side? That’s what I am reading at the serial monitor:
Connecting to APN: giffgaff.com OK
Connecting to xxxxxxxxxxxxxxxxxxxxxxxxxxx.net OK
Performing HTTP POST request…
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
function-execution-id: wyorn5o1ib5z
X-Cloud-Trace-Context: 42ffe95a4800312b7be39a82c2c6a5c6;o=1
Date: Fri, 12 Aug 2022 12:01:17 GMT
Server: Google Frontend
Content-Length: 9871
Connection: close
I just found my mistake! Your code is flawless! I mistyped the server details. I have included the path to the area where the data is stored instead of stopping where the data is received. Working well now! Tks!
This is nice, but I want to clarify something:
“http://192.168.1.106:1880/update-sensor” is not the server name.
192.168.1.106 is the name (in this case, already resolved as the IP address)
http is the protocol.
1880 is the port
/update-sensor is the path.
Источник
The ESP8266 and ESP32 have both a fully implemented TCP/IP stack and are capable of sending request and handling responses from a server using the HTTP protocol.
In this project we will demonstrate how to send data to a server and request data from a server using the ESP8266 as a client and printing the response on a serial terminal
- Information: HTTP
- GET vs. POST request – What is the difference?
- Materials needed
- Example 1: HTTP GET request with ESP8266
- Example 2: HTTP POST request with ESP8266
- Testing
- Wrap-Up
1) Information: HTTP
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web (i.e. internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of its request methods, error codes, and headers. The HTTP protocol is a request/response protocol based on the client/server based architecture where web browsers, robots and search engines, etc. act like HTTP clients, and the Web server acts as a server.
HTTP works as a request-response protocol between a client and server. Each Hypertext Transfer Protocol (HTTP) message is either a request or a response. A server listens on a connection for a request, parses each message received, interprets the message semantics in relation to the identified request target, and responds to that request with one or more response messages. A client constructs request messages to communicate specific intentions, examines received responses to see if the intentions were carried out, and determines how to interpret the results.
Client
The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP connection.
Server
The HTTP server responds with a status line, including the message’s protocol version and a success or error code, followed by a MIME-like message containing server information, entity meta information, and possible entity-body content.
2) GET vs. POST request – What is the difference?
Requests in HTML can use either GET or POST method by specifying method=”POST” or method=”GET” (default) in the <form> element. The method specified determines how form data is submitted to the server. When the method is GET, all form data is encoded into the URL, appended to the action URL as query string parameters. With POST, form data appears within the message body of the HTTP request.
Here is an overview of the main differences of both request methods.
GET Request | POST Request | |
History | Parameters remain in browser history because they are part of the URL | Parameters are not saved in browser history. |
---|---|---|
Bookmarked | Can be bookmarked. | Can not be bookmarked. |
BACK button/re-submit behaviour | GET requests are re-executed but may not be re-submitted to server if the HTML is stored in the browser cache. | The browser usually alerts the user that data will need to be re-submitted. |
Encoding type (enctype attribute) | application/x-www-form-urlencoded | multipart/form-data or application/x-www-form-urlencoded Use multipart encoding for binary data. |
Parameters | can send but the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64K | Can send parameters, including uploading files, to the server. |
Hacked | Easier to hack for script kiddies | More difficult to hack |
Restrictions on form data type | Yes, only ASCII characters allowed. | No restrictions. Binary data is also allowed. |
Security | GET is less secure compared to POST because data sent is part of the URL. So it’s saved in browser history and server logs in plaintext. | POST is a little safer than GET because the parameters are not stored in browser history or in web server logs. |
Restrictions on form data length | Yes, since form data is in the URL and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server. | No restrictions |
Usability | GET method should not be used when sending passwords or other sensitive information. | POST method used when sending passwords or other sensitive information. |
Visibility | GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send. | POST method variables are not displayed in the URL. |
Cached | Can be cached | Not cached |
So, basically we should know following points:
Simply put, GET requests are more useable; Use GET for safe actions and POST for unsafe actions. :
- GET requests can be cached
- GET requests can remain in the browser history
- GET requests can be bookmarked
- GET requests can be distributed & shared
- GET requests can be hacked
- Use POST when dealing with sensitive data.
- Use POST when dealing with long requests or sending larger data.
3) Materials needed
- NodeMcu ESP8266
- Computer / Raspberry Pi
4) Example 1: HTTP GET request with ESP8266
In this example the ESP8266 connects through WiFi to the internet and acts as a client sending HTTP GET requests to ESP8266-Shop.com. The URL is empty, which means no data is send along with the request URL. It’s basically the same request we send when we enter a web address in our browser. As response, the server sends the plain HTML in text format.
/* This sketch sends data via HTTP GET requests to esp8266-shop.com and returns the website in html format which is printed on the console */ #include <ESP8266WiFi.h> const char* ssid = "your-ssid"; //replace with your own wifi ssid const char* password = "your-password"; //replace with your own //wifi ssid password const char* host = "esp8266-shop.com"; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default, would try to act as both a client and an access-point and could cause network-issues with your other WiFi-devices on your WiFi-network. */ WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } int value = 0; void loop() { delay(5000); ++value; Serial.print("connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } // We now create a URI for the request //this url contains the informtation we want to send to the server //if esp8266 only requests the website, the url is empty String url = "/"; /* url += "?param1="; url += param1; url += "?param2="; url += param2; */ Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1rn" + "Host: " + host + "rn" + "Connection: closernrn"); unsigned long timeout = millis(); while (client.available() == 0) { if (millis() - timeout > 5000) { Serial.println(">>> Client Timeout !"); client.stop(); return; } } // Read all the lines of the reply from server and print them to Serial while (client.available()) { String line = client.readStringUntil('r'); Serial.print(line); } Serial.println(); Serial.println("closing connection"); }
5) Example 2: HTTP POST request with ESP8266
In this example the ESP8266 connects through WiFi to the internet and acts as a client sending HTTP POST requests to postman-echo.com that is a free service that echoes POST and GEt requests back to the sender. The URL is “/posts” without containing any data, but the payload contains the value of an ADC reading. Since the server in this case expects data in a POST request and will send the payload data back in a response message to the ESP8266.
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> const char* ssid = "YOUR SSID"; const char* password = "YOUR SSID PASSWORD"; const char* host = "postman-echo.com"; //edit the host adress, ip address etc. String url = "/post/"; int adcvalue=0; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default, would try to act as both a client and an access-point and could cause network-issues with your other WiFi-devices on your WiFi-network. */ WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } int value = 0; void loop() { delay(5000); adcvalue=analogRead(A0); //Read Analog value of pin A0 Serial.print("connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } Serial.print("Requesting URL: "); Serial.println(url); //Post Data String postData = "adcreading=" + String(adcvalue); String address = host + url; HTTPClient http; http.begin(address); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); auto httpCode = http.POST(postData); Serial.println(httpCode); //Print HTTP return code String payload = http.getString(); Serial.println(payload); //Print request response payload http.end(); //Close connection Serial.println(); Serial.println("closing connection"); }
6) Testing
Upload the code and open serial monitor, in case of any problem it will show errors. The ESP8266 will print the request and the response of the GET and POST requests.
7) Wrap-Up
As we have seen in both examples, it is quite easy to make GET and POST requests from the ESP8266. The only tricky part is to manipulate Strings in the URL or the payload (in case of the POST request).
We learned that simple requests that are shorter than 2000 characters and do not contain sensitive data such as passwords can be done via GET requests. Sensitive data and larger data must be send and received by POST requests.
Bear in mind that using a POST request alone does not make your communication secure. It just makes sure that sensitive data is not in in the request URL. Thus, we make sure that this data cannot be cached, or bookmarked. However, if a third party is able to catch the requests and responses, he will be able to read the full content.
In order to have a secure communication, the request needs to be encrypted via SSL/TLS (https vs. http), such that only sender and receiver are able to read the content of each message.