http request for get json

Dependencies:   HTTPClient

main.cpp

Committer:
quxiaorui
Date:
2020-11-08
Revision:
1:0437cdff5724
Parent:
0:cd14a0821140

File content as of revision 1:0437cdff5724:

#include "mbed.h"
#include "HTTPClient.h"
#include "errno.h"
NetworkInterface *net = NetworkInterface::get_default_instance();
void get_json(char *url)
{
  char buffer[256];
  HTTPJson httpjson(buffer, 256);
  HTTPClient http(net);
  HTTPResult result = http.get(url, &httpjson);
  if (result == HTTP_OK)
  {
    printf("Result Json.\n%s\r\n", buffer);
  }
  else
  {
    printf("Error during download %d\r\n", result);
  }
}
int main()
{
#ifdef MBED_MAJOR_VERSION
  printf("Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
#endif
  printf("Mbed OS http get json example\n");
  nsapi_size_or_error_t result = net->connect();
  if (result != 0)
  {
    printf("Error! net->connect() returned: %d\n", result);
    return result;
  }
  // Show the network address
  SocketAddress a;
  net->get_ip_address(&a);
  printf("IP address: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");
  net->get_netmask(&a);
  printf("Netmask: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");
  net->get_gateway(&a);
  printf("Gateway: %s\n\n", a.get_ip_address() ? a.get_ip_address() : "None");
  // Get Json
  get_json((char *)"http://ip-api.com/json/?fields=status,query");
  net->disconnect();
}