xiaorui qu / Mbed OS mbed-demo-http-get-json

Dependencies:   HTTPClient

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 "errno.h"
00004 NetworkInterface *net = NetworkInterface::get_default_instance();
00005 void get_json(char *url)
00006 {
00007   char buffer[256];
00008   HTTPJson httpjson(buffer, 256);
00009   HTTPClient http(net);
00010   HTTPResult result = http.get(url, &httpjson);
00011   if (result == HTTP_OK)
00012   {
00013     printf("Result Json.\n%s\r\n", buffer);
00014   }
00015   else
00016   {
00017     printf("Error during download %d\r\n", result);
00018   }
00019 }
00020 int main()
00021 {
00022 #ifdef MBED_MAJOR_VERSION
00023   printf("Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
00024 #endif
00025   printf("Mbed OS http get json example\n");
00026   nsapi_size_or_error_t result = net->connect();
00027   if (result != 0)
00028   {
00029     printf("Error! net->connect() returned: %d\n", result);
00030     return result;
00031   }
00032   // Show the network address
00033   SocketAddress a;
00034   net->get_ip_address(&a);
00035   printf("IP address: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");
00036   net->get_netmask(&a);
00037   printf("Netmask: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");
00038   net->get_gateway(&a);
00039   printf("Gateway: %s\n\n", a.get_ip_address() ? a.get_ip_address() : "None");
00040   // Get Json
00041   get_json((char *)"http://ip-api.com/json/?fields=status,query");
00042   net->disconnect();
00043 }