|
| 1 | +/** |
| 2 | + PostHTTPClient.ino |
| 3 | +
|
| 4 | + Created on: 21.11.2016 |
| 5 | +
|
| 6 | +*/ |
| 7 | + |
| 8 | +#include <ESP8266WiFi.h> |
| 9 | +#include <ESP8266HTTPClient.h> |
| 10 | + |
| 11 | +#define USE_SERIAL Serial |
| 12 | + |
| 13 | +/* this can be run with an emulated server on host: |
| 14 | + cd esp8266-core-root-dir |
| 15 | + cd tests/host |
| 16 | + make ../../libraries/ESP8266WebServer/examples/PostServer/PostServer |
| 17 | + bin/PostServer/PostServer |
| 18 | + then put your PC's IP address in SERVER_IP below, port 9080 (instead of default 80): |
| 19 | +*/ |
| 20 | +//#define SERVER_IP "10.0.1.7:9080" // PC address with emulation on host |
| 21 | +#define SERVER_IP "192.168.1.42" |
| 22 | + |
| 23 | +#ifndef STASSID |
| 24 | +#define STASSID "your-ssid" |
| 25 | +#define STAPSK "your-password" |
| 26 | +#endif |
| 27 | + |
| 28 | +void setup() { |
| 29 | + |
| 30 | + USE_SERIAL.begin(115200); |
| 31 | + |
| 32 | + USE_SERIAL.println(); |
| 33 | + USE_SERIAL.println(); |
| 34 | + USE_SERIAL.println(); |
| 35 | + |
| 36 | + WiFi.begin(STASSID, STAPSK); |
| 37 | + |
| 38 | + while (WiFi.status() != WL_CONNECTED) { |
| 39 | + delay(500); |
| 40 | + USE_SERIAL.print("."); |
| 41 | + } |
| 42 | + USE_SERIAL.println(""); |
| 43 | + USE_SERIAL.print("Connected! IP address: "); |
| 44 | + USE_SERIAL.println(WiFi.localIP()); |
| 45 | + |
| 46 | +} |
| 47 | + |
| 48 | +void loop() { |
| 49 | + // wait for WiFi connection |
| 50 | + if ((WiFi.status() == WL_CONNECTED)) { |
| 51 | + |
| 52 | + WiFiClient client; |
| 53 | + HTTPClient http; |
| 54 | + |
| 55 | + USE_SERIAL.print("[HTTP] begin...\n"); |
| 56 | + // configure traged server and url |
| 57 | + http.begin(client, "http://" SERVER_IP "/postplain/"); //HTTP |
| 58 | + http.addHeader("Content-Type", "application/json"); |
| 59 | + |
| 60 | + USE_SERIAL.print("[HTTP] POST...\n"); |
| 61 | + // start connection and send HTTP header and body |
| 62 | + int httpCode = http.POST("{\"hello\":\"world\"}"); |
| 63 | + |
| 64 | + // httpCode will be negative on error |
| 65 | + if (httpCode > 0) { |
| 66 | + // HTTP header has been send and Server response header has been handled |
| 67 | + USE_SERIAL.printf("[HTTP] POST... code: %d\n", httpCode); |
| 68 | + |
| 69 | + // file found at server |
| 70 | + if (httpCode == HTTP_CODE_OK) { |
| 71 | + const String& payload = http.getString(); |
| 72 | + USE_SERIAL.println("received payload:\n<<"); |
| 73 | + USE_SERIAL.println(payload); |
| 74 | + USE_SERIAL.println(">>"); |
| 75 | + } |
| 76 | + } else { |
| 77 | + USE_SERIAL.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str()); |
| 78 | + } |
| 79 | + |
| 80 | + http.end(); |
| 81 | + } |
| 82 | + |
| 83 | + delay(10000); |
| 84 | +} |
0 commit comments