Arduino: Examples of POST request with ESP8266WiFi.h

Created on 8 Jan 2016  Â·  31Comments  Â·  Source: esp8266/Arduino

Hey,

I have been trawling the web looking for an example of a POST request using the ESP8266WiFi.h library. Please can you help.

Thanks
James

Most helpful comment

Hi,

I worked on it for days to find the perfect example for the library you want to use. Let me give you an example:

Serial.begin(115200);
while(!Serial){}
WiFiClient client;
const char* host="http://jsonplaceholder.typicode.com/";
String PostData = "title=foo&body=bar&userId=1";

if (client.connect(host, 80)) {

client.println("POST /posts HTTP/1.1");
client.println("Host: jsonplaceholder.typicode.com");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

long interval = 2000;
unsigned long currentMillis = millis(), previousMillis = millis();

while(!client.available()){

  if( (currentMillis - previousMillis) > interval ){

    Serial.println("Timeout");
    blinkLed.detach();
    digitalWrite(2, LOW);
    client.stop();     
    return;
  }
  currentMillis = millis();
}

while (client.connected())
{
  if ( client.available() )
  {
    char str=client.read();
   Serial.println(str);
  }      
}

}

This is a proper working example for POST request using the library you mentioned and you can verify the the particular example using chrome extension POSTMAN.Let me show you the preview of the POST request i just created:

POST /posts HTTP/1.1
Host: jsonplaceholder.typicode.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

title=foo&body=bar&userId=1

This is the post request i just created.

Happy Coding :)

All 31 comments

You can read up on HTTP. A POST request sends its payload in the body- encoding varies on what youre trying to do (file upload). Typcial case is form encoding the data. Dont have an example thought, sorry.

Example POST to Azure

void senddata(JsonObject& json)
{
// POST URI
client.print("POST /tables/"); client.print(table_name); client.println(" HTTP/1.1");
// Host header
client.print("Host:"); client.println(mserver);
// Azure Mobile Services application key
client.print("X-ZUMO-APPLICATION:"); client.println(ams_key);
// JSON content type
client.println("Content-Type: application/json");
// Content length
int length = json.measureLength();
client.print("Content-Length:"); client.println(length);
// End of headers
client.println();
// POST message body
//json.printTo(client); // very slow ??
String out;
json.printTo(out);
client.println(out);
}

Hi,

I worked on it for days to find the perfect example for the library you want to use. Let me give you an example:

Serial.begin(115200);
while(!Serial){}
WiFiClient client;
const char* host="http://jsonplaceholder.typicode.com/";
String PostData = "title=foo&body=bar&userId=1";

if (client.connect(host, 80)) {

client.println("POST /posts HTTP/1.1");
client.println("Host: jsonplaceholder.typicode.com");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

long interval = 2000;
unsigned long currentMillis = millis(), previousMillis = millis();

while(!client.available()){

  if( (currentMillis - previousMillis) > interval ){

    Serial.println("Timeout");
    blinkLed.detach();
    digitalWrite(2, LOW);
    client.stop();     
    return;
  }
  currentMillis = millis();
}

while (client.connected())
{
  if ( client.available() )
  {
    char str=client.read();
   Serial.println(str);
  }      
}

}

This is a proper working example for POST request using the library you mentioned and you can verify the the particular example using chrome extension POSTMAN.Let me show you the preview of the POST request i just created:

POST /posts HTTP/1.1
Host: jsonplaceholder.typicode.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

title=foo&body=bar&userId=1

This is the post request i just created.

Happy Coding :)

any reason not to use the HTTP client ?

HTTPClient http;
http.begin("http://jsonplaceholder.typicode.com/posts");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http.POST("title=foo&body=bar&userId=1");
http.writeToStream(&Serial);
http.end();

https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPClient

Yeah HTTP client is fine I'm using something like this (not sure it's the best way but rocks) with prepared URL for emoncms

/* ======================================================================
Function: httpPost
Purpose : Do a http post
Input   : hostname
          port
          url
Output  : true if received 200 OK
Comments: -
====================================================================== */
boolean httpPost(char * host, uint16_t port, char * url)
{
  HTTPClient http;
  bool ret = false;

  unsigned long start = millis();

  // configure target server and url
  http.begin(host, port, url, port==443 ? true : false); 
  //http.begin("http://emoncms.org/input/post.json?node=20&apikey=apikey&json={PAPP:100}");

  Debugf("http%s://%s:%d%s => ", port==443?"s":"", host, port, url);

  // start connection and send HTTP header
  int httpCode = http.GET();
  if(httpCode) {
      // HTTP header has been send and Server response header has been handled
      Debug(httpCode);
      Debug(" ");
      // file found at server
      if(httpCode == 200) {
        String payload = http.getString();
        Debug(payload);
        ret = true;
      }
  } else {
      DebugF("failed!");
  }
  Debugf(" in %d ms\r\n",millis()-start);
  return ret;
}

Should accept more than just 200 OK as a valid response code. Most common code used to indicate success with REST is 201 Created.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

@mrbubble62
Thanks for this useful information, I never saw this code, good to know!
Anyway, it was just an example for Emoncms, so this one should be better ;-)

if( httpCode => 200 && httpCode < 300 ) {

@thorburn1 This is not about library for Arduino UNO. This is an HTTPClient library which runs on the ESP8266 itself, no external Arduino attached.

How do I write the url for http.GET() that have a space in between letters such as example.com/default/datetime=2016-10-23 12:03:33

try adding a + sign between the two instead of the space

Try using + where space would be. It might work.

On Oct 23, 2016 11:56 AM, "sopan-sarkar" [email protected] wrote:

How do I write the url for http.GET() that have a space in between letters
such as example.com/default/datetime=2016-10-23 12:03:33

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/esp8266/Arduino/issues/1390#issuecomment-255572106,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AS3BTuWzhzCVbht8_uxmxyjQnV1br1f6ks5q2v4jgaJpZM4HBfkR
.

Hello, can someone help me with this...

`

include

include

include

const int tmpPin = 9;
OneWire one(tmpPin);
DallasTemperature sensor(&one);
SoftwareSerial wifi(4, 2);

String red = "clave";
String pass = "pass";

String serv = "maleconjuarez.com.es";
String url = "/temperita";

void setup()
{
Serial.begin(115200);
wifi.begin(115200);
sensor.begin();
resetear();

}

void resetear()
{
wifi.println("AT+RST");
delay(1000);
if(wifi.find("OK")) Serial.println("Modulo reiniciado");

}

void loop()
{
ConnectWifi();
VincularTCP();
Temp();
resetear();

}

void ConnectWifi()
{
String conectar = "AT+CWJAP=\"" + red +"\",\"" + pass+ "\"";
wifi.println(conectar);
delay(4000);
if(wifi.find("OK"))
{
Serial.println("Conectado!");
}
else
Serial.println("Paso 1 no completado");

}

void VincularTCP()
{
wifi.println( "AT+CIPSTART=\"TCP\",\""); //Crear el comando para comenzar una conexion TCP
delay(2000); //Darle 2 segundos para responder

if(Serial.find("ERROR")){
return; //No se pudo conectar
}

}

void Temp()
{
sensor.requestTemperatures(); //Escaneo de temperatura
float tmp = sensor.getTempCByIndex(0);

//URL Temperatura
//URL: maleconjuaresz.com.es:8901/temperita?Id_temp=0&Id_Device=1&Valor=00.00&Temperatura_Action=Insert
String urluno = String("Id_temp=0&Id_Device=2&Valor=");
String temp = String(tmp);
String urldos = String("&Temperatura_Action=Insert");
String urlfinal = String(String(urluno) + String(tmp) + String(urldos));

wifi.println("AT+CIPSTART=\"TCP\",\"" + serv + "\",8901");//Inicia la conexión TCP
if(wifi.find("OK"))
{
  Serial.println("Conectado al servidor");
}

wifi.println("POST /temperita HTTP/1.0");                   //Petición de HTTP POST Temperatura
wifi.println("Host: maleconjuarez.com.es:8901");
wifi.println("Content-Type: application/x-www-form-urlencoded");
//wifi.print("Content-Length: ");
wifi.println("AT+CIPSEND=");//determine the number of caracters to be sent.
wifi.println(urlfinal.length());
wifi.println();
wifi.println(urlfinal);

}
`
Doesn't send anything!

First, Use the Postman Google Chrome extension app and check wether it sends the data or not.

Does anybody have an example of using ESP8266HTTPClient.POST with a multipart or octet stream. I'm trying to POST a JPEG.

Does anybody have solution for one esp8266 as a client and other esp8266 as server where client send data and server accept that data and server send response after receiving data

There is a post online claiming he achieved this over mqtt architecture.
But didn't find any source code till date.

On Jul 6, 2017 11:34 AM, "sagar87966" notifications@github.com wrote:

Does anybody have solution for one esp8266 as a client and other esp8266
as server where client send data and server accept that data and server
send response after receiving data

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/esp8266/Arduino/issues/1390#issuecomment-313304177,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AS3BTolrfRrt9tu_JRgCkCwPlQ8CkEDIks5sLHjWgaJpZM4HBfkR
.

This is the best I could do. I manually created the multi-part POST and sent the buffer with the WiFi Client, like some other people have suggested. https://github.com/adjavaherian/solar-server/blob/master/lib/Poster/Poster.cpp

Hello guys, I want to post the .bin file (aka sketch) between 2 ESP-s. So first ESP will post its own sketch(firmware) to second ESP's /update url to update its firmware.
How it is possible? I'll be glad if you redirect me. Thanks.

@diffstorm I guess what you are trying to do it OTA.
check out ESP8266HttpUpdate and ESP8266HttpUpdateServer example sketches.

@HugoSH I know them indeed, my idea is based them. I have studied both classes you pointed. How an ESP can upload it's own firmware (.bin) to another ESP's ESP8266HttpUpdateServer page (url/update)? That was my question. Thanks.

Hello!

Anybody experienced in POSTing a file from SPIFFS?

void bing() {
HTTPClient c;
File f = SPIFFS.open("/test.wav", "r");
int n = f.size();
Serial.println("Filesize: " + (String) n);
int rc = c.begin("https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=de-de&format=simple","73:8B:62:FA:64:66:53:9F:37:89:24:C2:D4:7D:09:34:78:7A:6B:60");
Serial.println("begin: " + (String) rc);
c.addHeader("Transfer-Encoding","chunked");
c.addHeader("Connection","close");
c.addHeader("Ocp-Apim-Subscription-Key", "mymicrosoftkey");
c.addHeader("Content-type", "audio/wav; codec=audio/pcm; samplerate=16000");

rc = c.sendRequest("POST", &f, n);
Serial.println("send: " + (String) rc);
Serial.println(c.getString());
c.end();
f.close();

Serial.println("Finished");
}

I always get ERROR .3. The file os readable, n has the correct size:

begin: 1
send: -3

Finished

Hi, It's possible to send a POST request with Object.addHeader("Content-Type", "application/json") in ESP8266httpclient library? I'm trying to do this but doesn't work.

Hello guys!
I'm a begginer at programming with ESP8266, Arduino IDE and C++.
I've made small progress by connecting the ESP8266 to my home wifi, however I'd like to send some data to my uncle web server through a POST request and I'm not making any progress.
I've already tried to send the data using the WiFiClient library and the ESP8266HTTPClient library but none of them worked. I'm starting to think that maybe the web server data that my uncle gave me are not correct.
Here is the data he gave me:

POST /rods/airlo/firstmodule/ HTTP/1.1

Host: iotsystem.synology.me:314

Content-Type: application/json

Cache-Control: no-cache

Postman-Token: (it's a long code with numbers and letters but I won't poste here for security reasons)

The way I see there's only two reasons why I can't send the data: I'm not puting these data correctly in my code or he gave me wrong data.
Can anyone help me?

Thanks a lot!!

And your code is...?

Em Qui, 19 de abr de 2018 22:34, chakibe notifications@github.com
escreveu:

Hello guys!
I'm a begginer at programming with ESP8266, Arduino IDE and C++.
I've made small progress by connecting the ESP8266 to my home wifi,
however I'd like to send some data to my uncle web server through a POST
request and I'm not making any progress.
I've already tried to send the data using the WiFiClient library and the
ESP8266HTTPClient library but none of them worked. I'm starting to think
that maybe the web server data that my uncle gave me are not correct.
Here is the data he gave me:

POST /rods/airlo/firstmodule/ HTTP/1.1

Host: iotsystem.synology.me:314

Content-Type: application/json

Cache-Control: no-cache

Postman-Token: (it's a long code with numbers and letters but I won't
poste here for security reasons)

The way I see there's only two reasons why I can't send the data: I'm not
puting these data correctly in my code or he gave me wrong data.
Can anyone help me?

Thanks a lot!!

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/esp8266/Arduino/issues/1390#issuecomment-382935974,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AMptcf4dwg21daVftEv2Ap-hxNYFFoIiks5tqTsjgaJpZM4HBfkR
.

I tried to write just like this, like the example above

Serial.begin(115200);
while(!Serial){}
WiFiClient client;
const char* host="http://jsonplaceholder.typicode.com/";
String PostData = "title=foo&body=bar&userId=1";

if (client.connect(host, 80)) {

client.println("POST /rods/airlo/firstmodule/ HTTP/1.1");
client.println("Host: iotsystem.synology.me:314");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

long interval = 2000;
unsigned long currentMillis = millis(), previousMillis = millis();

while(!client.available()){

if( (currentMillis - previousMillis) > interval ){

Serial.println("Timeout");
blinkLed.detach();
digitalWrite(2, LOW);
client.stop();     
return;

}
currentMillis = millis();
}

while (client.connected())
{
if ( client.available() )
{
char str=client.read();
Serial.println(str);
}
}
}

However it's always an HTTP error code

Youre posting urlencoded, not json!

Use a linux-system:

First edit http-server.txt:

HTTP/1.0 200 OK
Content-Length: 10

Hallo Welt

nc -l 80 < http-server.txt

And - by the way - why do you program your own http-client? There is one in the library!

Greetungs

Winfried

Am 23.04.2018 um 03:36 schrieb chakibe <[email protected]notifications@github.com>:

I tried to write just like this, like the example above

Serial.begin(115200);
while(!Serial){}
WiFiClient client;
const char* host="http://jsonplaceholder.typicode.com/";
String PostData = "title=foo&body=bar&userId=1";

if (client.connect(host, 80)) {

client.println("POST /rods/airlo/firstmodule/ HTTP/1.1");
client.println("Host: iotsystem.synology.me:314http://iotsystem.synology.me:314");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

long interval = 2000;
unsigned long currentMillis = millis(), previousMillis = millis();

while(!client.available()){

if( (currentMillis - previousMillis) > interval ){

Serial.println("Timeout");
blinkLed.detach();
digitalWrite(2, LOW);
client.stop();
return;

}
currentMillis = millis();
}

while (client.connected())
{
if ( client.available() )
{
char str=client.read();
Serial.println(str);
}
}
}

However it's always an HTTP error code

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHubhttps://github.com/esp8266/Arduino/issues/1390#issuecomment-383430774, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AfaTKVzRUaeafrKTPIMxX0ShhnVwqvyMks5trTAhgaJpZM4HBfkR.

hi
I write this code for connect to url with esp8266.
but when it connect to adsl, show me old data. i can not clean buffer of esp8266.
please help me.
excuse me for bad English writing.
`#include

include

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

void setup () {

Serial.begin(115200);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(500);
Serial.print(".");

}

}

void loop() {

if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient
http.begin("http://www.eleknow.com/wp-content/wot/micro_side.php");  //Specify request destination
int httpCode = http.GET();                                                                  //Send the request

if (httpCode > 0) { //Check the returning code
  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload
}

http.end();   //Close connection

}

delay(30000); //Send a request every 30 seconds

}`

Hi,
I have been reading all kinds of posts regarding the POST to a PHP file but just can't get it to work.

The PHP file on the server works for sure - when i run it via the browser, it creates the HTML file.

Here is the INO file i'm using, it's not producing any error messages, and connects to the client server but it does not transfer the DATA variable.

#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
`#include

include

include //https://github.com/tzapu/WiFiManager`

WiFiClient client;

const char server_name[] = SUBDOMAIN.net";
String data;
String Val, Time, State;

void setup() { Serial.begin(115200); WiFiManager wifiManager; wifiManager.autoConnect("AutoConnectAP"); Serial.println("connected:)"); }
void loop() {
int V1 = 1234;
int V2 = 5678;

    String data = "V1="
      +                        (String) V1
      +  "&V2="  +(String) V2 ;        

    Serial.println("\nStarting connection to server..."); 
      // if you get a connection, report back via serial:
    if (client.connect(server_name, 80)) 
    {
        Serial.println("connected to server");
        //WiFi.printDiag(Serial);
        delay(1000);   
        client.println("POST /file.php HTTP/1.1"); 
        client.println("Host: server_name");        
        client.println("User-Agent:ESP8266/1.0");
        client.println("Connection: close");                                
         client.println("Content-Type: application/x-www-form-urlencoded");
         int dataL = data.length();
         client.print("Content-Length: ");
         client.println(dataL);
         client.print("\n\n");
         client.print(data);

         Serial.println("\n");
         Serial.println("My data string im POSTing looks like this: ");
         Serial.println(data);
         Serial.println("And it is this many bytes: ");
         Serial.println(data.length());       
         delay(2000);            
         client.stop(); 
    } //if client.connect

} //loop

and the PHP file:

<?php

file_put_contents('display.html', $TimeStamp, FILE_APPEND);

if( $_REQUEST["V1"] || $_REQUEST["V2"] )
{ echo " Value1 is: ". $_REQUEST['V1']. "<br />"; echo " Value2 is: ". $_REQUEST['V2']. " <br />"; }

$var1 = $_REQUEST['V1'];

$var2 = $_REQUEST['V2'];

$WriteMyRequest= "<p> Value1 is : " . $var1 . " </p>".

        `    "<p> And Value2 is : " . $var2 . "  </p><br/>"; `

file_put_contents('display.html', $WriteMyRequest, FILE_APPEND);

?>

(it didn't go so well with code sections quotes...)

any advice?

Tahnk you.

Hello!

First a tipp for debugging:

nc -l 80
(stop your webserver before or use another port like 8888 or 8080 in Your sketch
You will see your HTTP-Request!

Second a question: Why doun't You use esp8266httpclient instead? It's not necessarry
to re-invent the wheel - in this thase the HTTP-Client.

Winfried

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Chagui- picture Chagui-  Â·  3Comments

markusschweitzer picture markusschweitzer  Â·  3Comments

hulkco picture hulkco  Â·  3Comments

rudydevolder picture rudydevolder  Â·  3Comments

mechanic98 picture mechanic98  Â·  3Comments