Arduino icon indicating copy to clipboard operation
Arduino copied to clipboard

Examples of POST request with ESP8266WiFi.h

Open jim-at-jibba opened this issue 10 years ago • 31 comments

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

jim-at-jibba avatar Jan 08 '16 21:01 jim-at-jibba

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.

andig avatar Jan 08 '16 22:01 andig

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

mrbubble62 avatar Jan 09 '16 06:01 mrbubble62

easy way: https://github.com/esp8266/Arduino/issues/1159#issuecomment-162331317

Links2004 avatar Jan 09 '16 11:01 Links2004

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

sukhmeet032795 avatar Jan 10 '16 12:01 sukhmeet032795

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

Links2004 avatar Jan 10 '16 13:01 Links2004

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

hallard avatar Jan 12 '16 14:01 hallard

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 avatar Jan 12 '16 19:01 mrbubble62

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

hallard avatar Jan 12 '16 20:01 hallard

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

igrr avatar Jun 06 '16 10:06 igrr

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

sopan-sarkar avatar Oct 23 '16 06:10 sopan-sarkar

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

rohit-rcrohit7 avatar Oct 24 '16 20:10 rohit-rcrohit7

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 .

rohit-rcrohit7 avatar Oct 25 '16 21:10 rohit-rcrohit7

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!

rezamar555 avatar Oct 27 '16 09:10 rezamar555

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

rohit-rcrohit7 avatar Oct 28 '16 07:10 rohit-rcrohit7

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

adjavaherian avatar Mar 23 '17 14:03 adjavaherian

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

sagar87966 avatar Jul 06 '17 06:07 sagar87966

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" [email protected] 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 .

rohit-rcrohit7 avatar Jul 06 '17 06:07 rohit-rcrohit7

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

adjavaherian avatar Jul 10 '17 03:07 adjavaherian

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 avatar Aug 23 '17 18:08 diffstorm

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

HugoSH avatar Aug 26 '17 09:08 HugoSH