Simple example demonstrating how to use GET & POST requests with the HTTP Client

Dependencies:   mbed mbed-rtos HTTPClient EthernetInterface

Committer:
donatien
Date:
Sun Aug 05 16:12:30 2012 +0000
Revision:
1:d263603373ac
Parent:
0:0e0debc29569
Child:
2:270e2d0bb85a
Public commit

Who changed what in which revision?

UserRevisionLine numberNew contents of line
donatien 0:0e0debc29569 1 #include "mbed.h"
donatien 0:0e0debc29569 2 #include "EthernetInterface.h"
donatien 0:0e0debc29569 3 #include "HTTPClient.h"
donatien 0:0e0debc29569 4
donatien 1:d263603373ac 5 EthernetInterface eth;
donatien 1:d263603373ac 6 HTTPClient http;
donatien 1:d263603373ac 7 char str[512];
donatien 1:d263603373ac 8
donatien 0:0e0debc29569 9 int main()
donatien 0:0e0debc29569 10 {
donatien 0:0e0debc29569 11 eth.init(); //Use DHCP
donatien 0:0e0debc29569 12
donatien 0:0e0debc29569 13 eth.connect();
donatien 0:0e0debc29569 14
donatien 0:0e0debc29569 15 //GET data
donatien 0:0e0debc29569 16 printf("Trying to fetch page...\n");
donatien 0:0e0debc29569 17 int ret = http.get("http://mbed.org/media/uploads/donatien/hello.txt", str, 128);
donatien 0:0e0debc29569 18 if (!ret)
donatien 0:0e0debc29569 19 {
donatien 0:0e0debc29569 20 printf("Page fetched successfully - read %d characters\n", strlen(str));
donatien 0:0e0debc29569 21 printf("Result: %s\n", str);
donatien 0:0e0debc29569 22 }
donatien 0:0e0debc29569 23 else
donatien 0:0e0debc29569 24 {
donatien 0:0e0debc29569 25 printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode());
donatien 0:0e0debc29569 26 }
donatien 1:d263603373ac 27
donatien 0:0e0debc29569 28 //POST data
donatien 0:0e0debc29569 29 HTTPMap map;
donatien 0:0e0debc29569 30 HTTPText text(str, 512);
donatien 0:0e0debc29569 31 map.put("Hello", "World");
donatien 0:0e0debc29569 32 map.put("test", "1234");
donatien 0:0e0debc29569 33 printf("Trying to post data...\n");
donatien 0:0e0debc29569 34 ret = http.post("http://httpbin.org/post", map, &text);
donatien 0:0e0debc29569 35 if (!ret)
donatien 0:0e0debc29569 36 {
donatien 0:0e0debc29569 37 printf("Executed POST successfully - read %d characters\n", strlen(str));
donatien 0:0e0debc29569 38 printf("Result: %s\n", str);
donatien 0:0e0debc29569 39 }
donatien 0:0e0debc29569 40 else
donatien 0:0e0debc29569 41 {
donatien 0:0e0debc29569 42 printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode());
donatien 0:0e0debc29569 43 }
donatien 0:0e0debc29569 44
donatien 0:0e0debc29569 45 eth.disconnect();
donatien 0:0e0debc29569 46
donatien 0:0e0debc29569 47 while(1) {
donatien 0:0e0debc29569 48 }
donatien 0:0e0debc29569 49 }