Simple example demonstrating how to use GET & POST requests with the HTTP Client
Dependencies: mbed mbed-rtos HTTPClient EthernetInterface
main.cpp
00001 #include "mbed.h" 00002 #include "EthernetInterface.h" 00003 #include "HTTPClient.h" 00004 00005 EthernetInterface eth; 00006 HTTPClient http; 00007 char str[512]; 00008 00009 int main() 00010 { 00011 eth.init(); //Use DHCP 00012 00013 eth.connect(); 00014 00015 //GET data 00016 printf("\nTrying to fetch page...\n"); 00017 int ret = http.get("http://mbed.org/media/uploads/donatien/hello.txt", str, 128); 00018 if (!ret) 00019 { 00020 printf("Page fetched successfully - read %d characters\n", strlen(str)); 00021 printf("Result: %s\n", str); 00022 } 00023 else 00024 { 00025 printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); 00026 } 00027 00028 //POST data 00029 HTTPMap map; 00030 HTTPText inText(str, 512); 00031 map.put("Hello", "World"); 00032 map.put("test", "1234"); 00033 printf("\nTrying to post data...\n"); 00034 ret = http.post("http://httpbin.org/post", map, &inText); 00035 if (!ret) 00036 { 00037 printf("Executed POST successfully - read %d characters\n", strlen(str)); 00038 printf("Result: %s\n", str); 00039 } 00040 else 00041 { 00042 printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); 00043 } 00044 00045 //PUT data 00046 strcpy(str, "This is a PUT test!"); 00047 HTTPText outText(str); 00048 //HTTPText inText(str, 512); 00049 printf("\nTrying to put resource...\n"); 00050 ret = http.put("http://httpbin.org/put", outText, &inText); 00051 if (!ret) 00052 { 00053 printf("Executed PUT successfully - read %d characters\n", strlen(str)); 00054 printf("Result: %s\n", str); 00055 } 00056 else 00057 { 00058 printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); 00059 } 00060 00061 //DELETE data 00062 //HTTPText inText(str, 512); 00063 printf("\nTrying to delete resource...\n"); 00064 ret = http.del("http://httpbin.org/delete", &inText); 00065 if (!ret) 00066 { 00067 printf("Executed DELETE successfully - read %d characters\n", strlen(str)); 00068 printf("Result: %s\n", str); 00069 } 00070 else 00071 { 00072 printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); 00073 } 00074 00075 eth.disconnect(); 00076 00077 while(1) { 00078 } 00079 }
Generated on Wed Jul 13 2022 19:05:08 by 1.7.2