mirror of
https://github.com/esp8266/Arduino.git
synced 2025-04-19 23:22:16 +03:00
POST http client example (#2704)
* POST http client example * avoid deprecated api * Update PostHttpClient.ino style, comments * Update PostHttpClient.ino
This commit is contained in:
parent
d012adc9bb
commit
eb6418f641
@ -0,0 +1,84 @@
|
||||
/**
|
||||
PostHTTPClient.ino
|
||||
|
||||
Created on: 21.11.2016
|
||||
|
||||
*/
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
|
||||
#define USE_SERIAL Serial
|
||||
|
||||
/* this can be run with an emulated server on host:
|
||||
cd esp8266-core-root-dir
|
||||
cd tests/host
|
||||
make ../../libraries/ESP8266WebServer/examples/PostServer/PostServer
|
||||
bin/PostServer/PostServer
|
||||
then put your PC's IP address in SERVER_IP below, port 9080 (instead of default 80):
|
||||
*/
|
||||
//#define SERVER_IP "10.0.1.7:9080" // PC address with emulation on host
|
||||
#define SERVER_IP "192.168.1.42"
|
||||
|
||||
#ifndef STASSID
|
||||
#define STASSID "your-ssid"
|
||||
#define STAPSK "your-password"
|
||||
#endif
|
||||
|
||||
void setup() {
|
||||
|
||||
USE_SERIAL.begin(115200);
|
||||
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
|
||||
WiFi.begin(STASSID, STAPSK);
|
||||
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
USE_SERIAL.print(".");
|
||||
}
|
||||
USE_SERIAL.println("");
|
||||
USE_SERIAL.print("Connected! IP address: ");
|
||||
USE_SERIAL.println(WiFi.localIP());
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// wait for WiFi connection
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
|
||||
WiFiClient client;
|
||||
HTTPClient http;
|
||||
|
||||
USE_SERIAL.print("[HTTP] begin...\n");
|
||||
// configure traged server and url
|
||||
http.begin(client, "http://" SERVER_IP "/postplain/"); //HTTP
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
|
||||
USE_SERIAL.print("[HTTP] POST...\n");
|
||||
// start connection and send HTTP header and body
|
||||
int httpCode = http.POST("{\"hello\":\"world\"}");
|
||||
|
||||
// httpCode will be negative on error
|
||||
if (httpCode > 0) {
|
||||
// HTTP header has been send and Server response header has been handled
|
||||
USE_SERIAL.printf("[HTTP] POST... code: %d\n", httpCode);
|
||||
|
||||
// file found at server
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
const String& payload = http.getString();
|
||||
USE_SERIAL.println("received payload:\n<<");
|
||||
USE_SERIAL.println(payload);
|
||||
USE_SERIAL.println(">>");
|
||||
}
|
||||
} else {
|
||||
USE_SERIAL.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||||
}
|
||||
|
||||
http.end();
|
||||
}
|
||||
|
||||
delay(10000);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user