Simple HTTP GET and POST with ESP8266.

Dependencies:   ESP8266Interface HTTPClient-SSL WebSocketClient mbed-rtos mbed

Fork of ESP8266_HTTP_HelloWorld by ESP8266

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "HTTPClient.h"
00003 #include "ESP8266Interface.h"
00004 #include "TCPSocketConnection.h"
00005 #include "Websocket.h"
00006 
00007 const char* ssid = "YOUR_SSID";
00008 const char* pwd = "YOUR_PWD";
00009 
00010 ESP8266Interface wifi(D8, D2, D7, ssid, pwd, 115200); // TX,RX,Reset,SSID,Password,Baud
00011 RawSerial pc(USBTX, USBRX); // tx, rx
00012 
00013 HTTPClient http;
00014 int main()
00015 {
00016     // 115200 baud rate to talk back to the PC
00017     pc.baud(115200);
00018     
00019     // need debug messages? check ESP8266Interface/ESP8266/ESP8266.cpp and change the #if 0 to #if 1
00020     
00021     pc.printf("\nTrying to connect to %s...!\r\n", ssid);
00022     wifi.init(); //Reset
00023     wifi.connect(); //Use DHCP
00024     
00025     pc.printf("Connected to WiFi. IP address = %s\r\n", wifi.getIPAddress());
00026     
00027     // For some reason DNS doesn't work. Just use raw IPs for now.
00028     // GET a page...
00029     {   
00030         char buffer[1024];
00031         HTTPResult ret = http.get("http://54.175.222.246/get", buffer, sizeof(buffer)); //IP address is httpbin.org/get
00032         if (ret == HTTP_OK) {
00033             pc.printf("Page fetched successfully - read %d characters\r\n", strlen(buffer));
00034             pc.printf("Result: %s\n\r", buffer);
00035         } else {
00036             pc.printf("Error - ret = %d - HTTP return code = %d\r\n", ret, http.getHTTPResponseCode());
00037         }
00038     }
00039     
00040     // POST to a page...
00041     {
00042         HTTPMap map;
00043         char buffer[1024];
00044         HTTPText inText(buffer, sizeof(buffer));
00045         map.put("Hello", "World");
00046         map.put("test", "1234");
00047         printf("\nTrying to POST data to httpbin.org/post...\r\n");
00048         HTTPResult ret = http.post("http://54.175.222.246/post", map, &inText); //IP address is httpbin.org/post
00049         if (ret == HTTP_OK)
00050         {
00051             pc.printf("Executed POST successfully - read %d characters\r\n", strlen(buffer));
00052             pc.printf("Result: %s\n\r", buffer);
00053         }
00054         else
00055         {
00056             pc.printf("Error - ret = %d - HTTP return code = %d\r\n", ret, http.getHTTPResponseCode());
00057         }
00058     }
00059 }
00060