Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Examples of POST request with ESP8266WiFi.h #1390

Closed
jim-at-jibba opened this issue Jan 8, 2016 · 31 comments
Closed

Examples of POST request with ESP8266WiFi.h #1390

jim-at-jibba opened this issue Jan 8, 2016 · 31 comments

Comments

@jim-at-jibba
Copy link

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

@andig
Copy link
Contributor

andig commented Jan 8, 2016

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.

@mrbubble62
Copy link

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);
}

@Links2004
Copy link
Collaborator

easy way:
#1159 (comment)

@sukhmeet032795
Copy link

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 :)

@Links2004
Copy link
Collaborator

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

@hallard
Copy link
Contributor

hallard commented Jan 12, 2016

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;
}

@mrbubble62
Copy link

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

@hallard
Copy link
Contributor

hallard commented Jan 12, 2016

@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 ) {

@igrr igrr closed this as completed Feb 29, 2016
@igrr
Copy link
Member

igrr commented Jun 6, 2016

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

@sopan-sarkar
Copy link

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

@rohit-rcrohit7
Copy link

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

@rohit-rcrohit7
Copy link

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

On Oct 23, 2016 11:56 AM, "sopan-sarkar" notifications@github.com 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
#1390 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AS3BTuWzhzCVbht8_uxmxyjQnV1br1f6ks5q2v4jgaJpZM4HBfkR
.

@rezamar555
Copy link

Hello, can someone help me with this...

`
#include <DallasTemperature.h>
#include <OneWire.h>
#include <SoftwareSerial.h>

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!

@rohit-rcrohit7
Copy link

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

@adjavaherian
Copy link

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

@sagar87966
Copy link

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

@rohit-rcrohit7
Copy link

rohit-rcrohit7 commented Jul 6, 2017 via email

@adjavaherian
Copy link

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

@diffstorm
Copy link

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.

@HugoSH
Copy link

HugoSH commented Aug 26, 2017

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

@diffstorm
Copy link

@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.

@Winfried-Bantel
Copy link

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

@iamalonso
Copy link

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.

@chakibe
Copy link

chakibe commented Apr 20, 2018

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!!

@iamalonso
Copy link

iamalonso commented Apr 20, 2018 via email

@chakibe
Copy link

chakibe commented Apr 23, 2018

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

@andig
Copy link
Contributor

andig commented Apr 23, 2018

Youre posting urlencoded, not json!

@Winfried-Bantel
Copy link

Winfried-Bantel commented Apr 23, 2018 via email

@sobhaniot
Copy link

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 <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

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

}`

@mardulis
Copy link

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 <DNSServer.h> #include <ESP8266WebServer.h> #include <WiFiManager.h> //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.

@Winfried-Bantel
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests