HTTP and HTTPS example application for Mbed OS 5
Dependencies: mbed-http
main-http-socket-reuse.cpp
00001 #include "select-demo.h" 00002 00003 #if DEMO == DEMO_HTTP_SOCKET_REUSE 00004 00005 #include "mbed.h" 00006 #include "network-helper.h" 00007 #include "http_request.h" 00008 00009 void dump_response(HttpResponse* res) { 00010 printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str()); 00011 00012 printf("Headers:\n"); 00013 for (size_t ix = 0; ix < res->get_headers_length(); ix++) { 00014 printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str()); 00015 } 00016 printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str()); 00017 } 00018 00019 int main() { 00020 NetworkInterface* network = connect_to_default_network_interface(); 00021 if (!network) { 00022 printf("Cannot connect to the network, see serial output\n"); 00023 return 1; 00024 } 00025 00026 // Create a TCP socket 00027 printf("\n----- Setting up TCP connection -----\n"); 00028 00029 TCPSocket* socket = new TCPSocket(); 00030 nsapi_error_t open_result = socket->open(network); 00031 if (open_result != 0) { 00032 printf("Opening TCPSocket failed... %d\n", open_result); 00033 return 1; 00034 } 00035 00036 nsapi_error_t connect_result = socket->connect("httpbin.org", 80); 00037 if (connect_result != 0) { 00038 printf("Connecting over TCPSocket failed... %d\n", connect_result); 00039 return 1; 00040 } 00041 00042 printf("Connected over TCP to httpbin.org:80\n"); 00043 00044 // Do a GET request to httpbin.org 00045 { 00046 HttpRequest* get_req = new HttpRequest(socket, HTTP_GET, "http://httpbin.org/status/418"); 00047 00048 // By default the body is automatically parsed and stored in a string, this is memory heavy. 00049 // To receive chunked response, pass in a callback as third parameter to 'send'. 00050 HttpResponse* get_res = get_req->send(); 00051 if (!get_res) { 00052 printf("HttpRequest failed (error code %d)\n", get_req->get_error()); 00053 return 1; 00054 } 00055 00056 printf("\n----- HTTP GET response -----\n"); 00057 dump_response(get_res); 00058 00059 delete get_req; 00060 } 00061 00062 // POST request to httpbin.org 00063 { 00064 HttpRequest* post_req = new HttpRequest(socket, HTTP_POST, "http://httpbin.org/post"); 00065 post_req->set_header("Content-Type", "application/json"); 00066 00067 const char body[] = "{\"hello\":\"world\"}"; 00068 00069 HttpResponse* post_res = post_req->send(body, strlen(body)); 00070 if (!post_res) { 00071 printf("HttpRequest failed (error code %d)\n", post_req->get_error()); 00072 return 1; 00073 } 00074 00075 printf("\n----- HTTP POST response -----\n"); 00076 dump_response(post_res); 00077 00078 delete post_req; 00079 } 00080 00081 socket->close(); 00082 delete socket; 00083 00084 wait(osWaitForever); 00085 } 00086 00087 #endif
Generated on Thu Jul 14 2022 06:47:14 by 1.7.2