Ciro Edgardo Romero
/
ISE_CEIoT
Proyecto integrador para asignatura de Especialización
Diff: main.cpp
- Revision:
- 36:00496782708e
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Sun Apr 11 02:17:20 2021 +0000 @@ -0,0 +1,86 @@ +//=====[Libraries]============================================================= + +// Se incluye como parte de la la clase HTTP +#include "select-demo.h" +#if DEMO == MAIN + +#include "mbed.h" +#include "http_request.h" +#include "network-helper.h" +#include "mbed_mem_trace.h" + +#include <stdio.h> +#include <string.h> + +//=====[Declaration and initialization of public global objects]=============== + +//=====[Declaration and initialization of public global variables]============= + +//=====[Declarations (prototypes) of public functions]========================= + +void response(HttpResponse* res); + +//=====[Main function, the program entry point after power on or reset]======== + +int main() { + printf("\n----- Ejemplo de test REST Client -----\n"); + // Conéctese a la red con la interfaz de red predeterminada + NetworkInterface* network = connect_to_default_network_interface(); + if (!network) { + printf("No se puede conectar a la red\n"); + return 1; + } + + // Se realiza la solicitud GET + { + // De forma predeterminada, el cuerpo se analiza y almacena automáticamente en un búfer, esto es una gran cantidad de memoria. + // Para recibir una respuesta fragmentada, pase una devolución de llamada como último parámetro al constructor. + HttpRequest* get_req = new HttpRequest(network, HTTP_GET, "http://192.168.1.75:3000/mediciones"); + + HttpResponse* get_res = get_req->send(); + if (!get_res) { + printf("HttpRequest failed (error code %d)\n", get_req->get_error()); + return 1; + } + + printf("\n----- HTTP GET response -----\n"); + response(get_res); + + delete get_req; + } + + // Solicitud POST + { + HttpRequest* post_req = new HttpRequest(network, HTTP_POST, "http://192.168.1.75:3000/mediciones"); + post_req->set_header("Content-Type", "application/json"); + + const char body[] = "{\"uuid\":\"12345\",\"valor\":12.34}"; + + HttpResponse* post_res = post_req->send(body, strlen(body)); + if (!post_res) { + printf("HttpRequest failed (error code %d)\n", post_req->get_error()); + return 1; + } + + printf("\n----- HTTP POST response -----\n"); + response(post_res); + + delete post_req; + } + + wait(osWaitForever); +} + +//=====[Implementations of public functions]=================================== + +void response(HttpResponse* res) { + printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str()); + + printf("Headers:\n"); + for (size_t ix = 0; ix < res->get_headers_length(); ix++) { + printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str()); + } + printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str()); +} + +#endif