HTTP and HTTPS example application for Mbed OS 5

Dependencies:   mbed-http

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main-http.cpp Source File

main-http.cpp

00001 #include "select-demo.h"
00002 
00003 #if DEMO == DEMO_HTTP
00004 
00005 #include "mbed.h"
00006 #include "http_request.h"
00007 #include "network-helper.h"
00008 #include "mbed_mem_trace.h"
00009 
00010 void dump_response(HttpResponse* res) {
00011     printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
00012 
00013     printf("Headers:\n");
00014     for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
00015         printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
00016     }
00017     printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
00018 }
00019 
00020 int main() {
00021     // Connect to the network with the default networking interface
00022     // if you use WiFi: see mbed_app.json for the credentials
00023     NetworkInterface* network = connect_to_default_network_interface();
00024     if (!network) {
00025         printf("Cannot connect to the network, see serial output\n");
00026         return 1;
00027     }
00028 
00029     // Do a GET request to httpbin.org
00030     {
00031         // By default the body is automatically parsed and stored in a buffer, this is memory heavy.
00032         // To receive chunked response, pass in a callback as last parameter to the constructor.
00033         HttpRequest* get_req = new HttpRequest(network, HTTP_GET, "http://httpbin.org/status/418");
00034 
00035         HttpResponse* get_res = get_req->send();
00036         if (!get_res) {
00037             printf("HttpRequest failed (error code %d)\n", get_req->get_error());
00038             return 1;
00039         }
00040 
00041         printf("\n----- HTTP GET response -----\n");
00042         dump_response(get_res);
00043 
00044         delete get_req;
00045     }
00046 
00047     // POST request to httpbin.org
00048     {
00049         HttpRequest* post_req = new HttpRequest(network, HTTP_POST, "http://httpbin.org/post");
00050         post_req->set_header("Content-Type", "application/json");
00051 
00052         const char body[] = "{\"hello\":\"world\"}";
00053 
00054         HttpResponse* post_res = post_req->send(body, strlen(body));
00055         if (!post_res) {
00056             printf("HttpRequest failed (error code %d)\n", post_req->get_error());
00057             return 1;
00058         }
00059 
00060         printf("\n----- HTTP POST response -----\n");
00061         dump_response(post_res);
00062 
00063         delete post_req;
00064     }
00065 
00066     wait(osWaitForever);
00067 }
00068 
00069 #endif