Demonstration program with support for the WNC M14A2A Cellular LTE Data Module added. An additional demonstration program was also added that shows a few other features (for chunked responses).

Dependencies:   easy-connect mbed-http

mbed-os-example-http(s) using WNC 14A2A Data Module

This application builds on the application provided by ARM (see https://developer.mbed.org/teams/sandbox/code/mbed-http/). It demonstrates how to make HTTP and HTTPS requests and parse the response from mbed OS 5.

There are a total of five demo's, which can be selected by modifying source/select-demo.h.

1. HTTP demo (DEMO_HTTP):

2. HTTPS demo (DEMO_HTTPS):

3. HTTP demo with socket re-use (DEMO_HTTP_SOCKET_REUSE).

  • Similar to the HTTP demo but reuses the socket for all interactions

4. HTTPS demo with socket re-use (DEMO_HTTPS_SOCKET_REUSE).

  • Similar to the HTTPS demo above

5. HTTP & HTTPS demo with socket re-use and chunked call-backs (DEMO_HTTPx)

Response parsing is done through [nodejs/http-parser](https://github.com/nodejs/http-parser).

To build

1. Open ``mbed_app.json`` and change the `network-interface` option to your connectivity method ([more info](https://github.com/ARMmbed/easy-connect)). 2. Build the project in the online compiler or using mbed CLI. 3. Flash the project to your development board. 4. Attach a serial monitor to your board to see the debug messages.

Entropy (or lack thereof)

On all platforms except the FRDM-K64F and FRDM-K22F the application is compiled without TLS entropy sources. This means that your code is inherently unsafe and should not be deployed to any production systems. To enable entropy, remove the `MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES` and `MBEDTLS_TEST_NULL_ENTROPY` macros from mbed_app.json.

Tested on

  • K64F with Ethernet.
  • NUCLEO_F411RE with ESP8266.
  • AT&T Cellular IoT Starter Kit with WNC M14A2A Cellular Data Module

The WNCInterface class currently supports the following version(s):

  • MPSS: M14A2A_v11.50.164451 APSS: M14A2A_v11.53.164451

License

This library is released under the Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License and may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Files at this revision

API Documentation at this revision

Comitter:
Jan Jongboom
Date:
Thu Feb 16 11:13:40 2017 +0100
Parent:
0:85fdc69bc10c
Child:
2:4b4ac59ff9b0
Commit message:
Add mbed-http

Changed in this revision

.hgignore Show annotated file Show diff for this revision Revisions of this file
source/mbed-http/http_parsed_url.h Show annotated file Show diff for this revision Revisions of this file
source/mbed-http/http_request.h Show annotated file Show diff for this revision Revisions of this file
source/mbed-http/http_request_builder.h Show annotated file Show diff for this revision Revisions of this file
source/mbed-http/http_response.h Show annotated file Show diff for this revision Revisions of this file
source/mbed-http/http_response_parser.h Show annotated file Show diff for this revision Revisions of this file
source/mbed-http/https_request.h Show annotated file Show diff for this revision Revisions of this file
--- a/.hgignore	Wed Feb 15 21:57:31 2017 +0100
+++ b/.hgignore	Thu Feb 16 11:13:40 2017 +0100
@@ -1,4 +1,4 @@
-.mbed
+^\.mbed$
 .vscode/
 mbed_settings.*
 BUILD/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/mbed-http/http_parsed_url.h	Thu Feb 16 11:13:40 2017 +0100
@@ -0,0 +1,71 @@
+#ifndef _MBED_HTTP_PARSED_URL_H_
+#define _MBED_HTTP_PARSED_URL_H_
+
+#include "http_parser.h"
+
+class ParsedUrl {
+public:
+    ParsedUrl(const char* url) {
+        struct http_parser_url parsed_url;
+        http_parser_parse_url(url, strlen(url), false, &parsed_url);
+
+        for (size_t ix = 0; ix < UF_MAX; ix++) {
+            const char* value;
+            if (parsed_url.field_set & (1 << ix)) {
+                value = (const char*)calloc(parsed_url.field_data[ix].len + 1, 1);
+                memcpy((void*)value, url + parsed_url.field_data[ix].off,
+                       parsed_url.field_data[ix].len);
+            }
+            else {
+                value = (const char*)calloc(1, 1);
+            }
+
+            switch ((http_parser_url_fields)ix) {
+                case UF_SCHEMA:   _schema   = value; break;
+                case UF_HOST:     _host     = value; break;
+                case UF_PATH:     _path     = value; break;
+                case UF_QUERY:    _query    = value; break;
+                case UF_USERINFO: _userinfo = value; break;
+                default:
+                    // PORT is already parsed, FRAGMENT is not relevant for HTTP requests
+                    free((void*)value);
+                    break;
+            }
+        }
+
+        _port = parsed_url.port;
+        if (!_port) {
+            if (strcmp(_schema, "https") == 0) {
+                _port = 443;
+            }
+            else {
+                _port = 80;
+            }
+        }
+    }
+
+    ~ParsedUrl() {
+        if (_schema) free((void*)_schema);
+        if (_host) free((void*)_host);
+        if (_path) free((void*)_path);
+        if (_query) free((void*)_query);
+        if (_userinfo) free((void*)_userinfo);
+    }
+
+    uint16_t port() const { return _port; }
+    const char* schema() const { return _schema; }
+    const char* host() const { return _host; }
+    const char* path() const { return _path; }
+    const char* query() const { return _query; }
+    const char* userinfo() const { return _userinfo; }
+
+private:
+    uint16_t _port;
+    const char* _schema;
+    const char* _host;
+    const char* _path;
+    const char* _query;
+    const char* _userinfo;
+};
+
+#endif // _MBED_HTTP_PARSED_URL_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/mbed-http/http_request.h	Thu Feb 16 11:13:40 2017 +0100
@@ -0,0 +1,180 @@
+#ifndef _HTTP_REQUEST_
+#define _HTTP_REQUEST_
+
+#include <string>
+#include <vector>
+#include <map>
+#include "http_parser.h"
+#include "http_response.h"
+#include "http_request_builder.h"
+#include "http_response_parser.h"
+#include "http_parsed_url.h"
+
+/**
+ * @todo:
+ *      - Userinfo parameter is not handled
+ *      - Allow socket re-use
+ */
+
+
+/**
+ * \brief HttpRequest implements the logic for interacting with HTTPS servers.
+ */
+class HttpRequest {
+public:
+    /**
+     * HttpRequest Constructor
+     *
+     * @param[in] aNetwork The network interface
+     * @param[in] aMethod HTTP method to use
+     * @param[in] url URL to the resource
+     * @param[in] aBodyCallback Callback on which to retrieve chunks of the response body.
+                                If not set, the complete body will be allocated on the HttpResponse object,
+                                which might use lots of memory.
+    */
+    HttpRequest(NetworkInterface* aNetwork, http_method aMethod, const char* url, Callback<void(const char *at, size_t length)> aBodyCallback = 0)
+        : network(aNetwork), method(aMethod), body_callback(aBodyCallback)
+    {
+        error = 0;
+        response = NULL;
+
+        parsed_url = new ParsedUrl(url);
+        request_builder = new HttpRequestBuilder(method, parsed_url);
+    }
+
+    /**
+     * HttpRequest Constructor
+     */
+    ~HttpRequest() {
+        // should response be owned by us? Or should user free it?
+        // maybe implement copy constructor on response...
+        if (response) {
+            delete response;
+        }
+
+        if (parsed_url) {
+            delete parsed_url;
+        }
+
+        if (request_builder) {
+            delete request_builder;
+        }
+    }
+
+    /**
+     * Execute the request and receive the response.
+     */
+    HttpResponse* send(const void* body = NULL, nsapi_size_t body_size = 0) {
+        if (response != NULL) {
+            // already executed this response
+            error = -2100; // @todo, make a lookup table with errors
+            return NULL;
+        }
+
+        error = 0;
+
+        TCPSocket socket;
+
+        nsapi_error_t open_result = socket.open(network);
+        if (open_result != 0) {
+            error = open_result;
+            return NULL;
+        }
+
+        nsapi_error_t connection_result = socket.connect(parsed_url->host(), parsed_url->port());
+        if (connection_result != 0) {
+            error = connection_result;
+            return NULL;
+        }
+
+        char* request = request_builder->build(body, body_size);
+        size_t request_size = strlen(request);
+
+        nsapi_size_or_error_t send_result = socket.send(request, request_size);
+
+        free(request);
+
+        if (send_result != request_size) {
+            error = send_result;
+            return NULL;
+        }
+
+        // Create a response object
+        response = new HttpResponse();
+        // And a response parser
+        HttpResponseParser parser(response, body_callback);
+
+        // Set up a receive buffer (on the heap)
+        uint8_t* recv_buffer = (uint8_t*)malloc(HTTP_RECEIVE_BUFFER_SIZE);
+
+        // TCPSocket::recv is called until we don't have any data anymore
+        nsapi_size_or_error_t recv_ret;
+        while ((recv_ret = socket.recv(recv_buffer, HTTP_RECEIVE_BUFFER_SIZE)) > 0) {
+            // Pass the chunk into the http_parser
+            size_t nparsed = parser.execute((const char*)recv_buffer, recv_ret);
+            if (nparsed != recv_ret) {
+                // printf("Parsing failed... parsed %d bytes, received %d bytes\n", nparsed, recv_ret);
+                error = -2101;
+                free(recv_buffer);
+                return NULL;
+            }
+            // No more chunks? break out of this loop
+            if (recv_ret < HTTP_RECEIVE_BUFFER_SIZE) {
+                break;
+            }
+        }
+        // error?
+        if (recv_ret < 0) {
+            error = recv_ret;
+            free(recv_buffer);
+            return NULL;
+        }
+
+        // When done, call parser.finish()
+        parser.finish();
+
+        // Free the receive buffer
+        free(recv_buffer);
+
+        // Close the socket
+        socket.close();
+
+        return response;
+    }
+
+    /**
+     * Set a header for the request.
+     *
+     * The 'Host' and 'Content-Length' headers are set automatically.
+     * Setting the same header twice will overwrite the previous entry.
+     *
+     * @param[in] key Header key
+     * @param[in] value Header value
+     */
+    void set_header(string key, string value) {
+        request_builder->set_header(key, value);
+    }
+
+    /**
+     * Get the error code.
+     *
+     * When send() fails, this error is set.
+     */
+    nsapi_error_t get_error() {
+        return error;
+    }
+
+private:
+    NetworkInterface* network;
+    http_method method;
+    Callback<void(const char *at, size_t length)> body_callback;
+
+    ParsedUrl* parsed_url;
+
+    HttpRequestBuilder* request_builder;
+    HttpResponse* response;
+
+    nsapi_error_t error;
+};
+
+#endif // _HTTP_REQUEST_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/mbed-http/http_request_builder.h	Thu Feb 16 11:13:40 2017 +0100
@@ -0,0 +1,101 @@
+#ifndef _MBED_HTTP_REQUEST_BUILDER_H_
+#define _MBED_HTTP_REQUEST_BUILDER_H_
+
+#include <string>
+#include <map>
+#include "http_parser.h"
+#include "http_parsed_url.h"
+
+class HttpRequestBuilder {
+public:
+    HttpRequestBuilder(http_method a_method, ParsedUrl* a_parsed_url)
+        : method(a_method), parsed_url(a_parsed_url)
+    {
+        set_header("Host", string(parsed_url->host()));
+    }
+
+    /**
+     * Set a header for the request
+     * If the key already exists, it will be overwritten...
+     */
+    void set_header(string key, string value) {
+        map<string, string>::iterator it = headers.find(key);
+
+        if (it != headers.end()) {
+            it->second = value;
+        }
+        else {
+            headers.insert(headers.end(), pair<string, string>(key, value));
+        }
+    }
+
+    char* build(const void* body, size_t body_size) {
+        const char* method_str = http_method_str(method);
+
+        if (body_size > 0) {
+            char buffer[10];
+            snprintf(buffer, 10, "%d", body_size);
+            set_header("Content-Length", string(buffer));
+        }
+
+        size_t size = 0;
+
+        // first line is METHOD PATH+QUERY HTTP/1.1\r\n
+        size += strlen(method_str) + 1 + strlen(parsed_url->path()) + strlen(parsed_url->query()) + 1 + 8 + 2;
+
+        // after that we'll do the headers
+        typedef map<string, string>::iterator it_type;
+        for(it_type it = headers.begin(); it != headers.end(); it++) {
+            // line is KEY: VALUE\r\n
+            size += it->first.length() + 1 + 1 + it->second.length() + 2;
+        }
+
+        // then the body, first an extra newline
+        size += 2;
+
+        // body
+        size += body_size;
+
+        // extra newline
+        size += 2;
+
+        // Now let's print it
+        char* req = (char*)calloc(size + 1, 1);
+        char* originalReq = req;
+
+        sprintf(req, "%s %s%s HTTP/1.1\r\n", method_str, parsed_url->path(), parsed_url->query());
+        req += strlen(method_str) + 1 + strlen(parsed_url->path()) + strlen(parsed_url->query()) + 1 + 8 + 2;
+
+        typedef map<string, string>::iterator it_type;
+        for(it_type it = headers.begin(); it != headers.end(); it++) {
+            // line is KEY: VALUE\r\n
+            sprintf(req, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
+            req += it->first.length() + 1 + 1 + it->second.length() + 2;
+        }
+
+        sprintf(req, "\r\n");
+        req += 2;
+
+        if (body_size > 0) {
+            sprintf(req, "%s", (char*)body);
+        }
+        req += body_size;
+
+        sprintf(req, "\r\n");
+        req += 2;
+
+        // Uncomment to debug...
+        // printf("----- BEGIN REQUEST -----\n");
+        // printf("%s", originalReq);
+        // printf("----- END REQUEST -----\n");
+
+        return originalReq;
+    }
+
+private:
+    http_method method;
+    ParsedUrl* parsed_url;
+    map<string, string> headers;
+};
+
+#endif // _MBED_HTTP_REQUEST_BUILDER_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/mbed-http/http_response.h	Thu Feb 16 11:13:40 2017 +0100
@@ -0,0 +1,90 @@
+#ifndef _MBED_HTTP_HTTP_RESPONSE
+#define _MBED_HTTP_HTTP_RESPONSE
+#include <string>
+#include <vector>
+#include "http_parser.h"
+
+using namespace std;
+
+class HttpResponse {
+public:
+    HttpResponse() {
+        status_code = 0;
+        concat_header_field = false;
+        concat_header_value = false;
+    }
+
+    void set_status(int a_status_code, string a_status_message) {
+        status_code = a_status_code;
+        status_message = a_status_message;
+    }
+
+    int get_status_code() {
+        return status_code;
+    }
+
+    string get_status_message() {
+        return status_message;
+    }
+
+    void set_header_field(string field) {
+        concat_header_value = false;
+
+        // headers can be chunked
+        if (concat_header_field) {
+            header_fields[header_fields.size() - 1] = header_fields[header_fields.size() - 1] + field;
+        }
+        else {
+            header_fields.push_back(field);
+        }
+
+        concat_header_field = true;
+    }
+
+    void set_header_value(string value) {
+        concat_header_field = false;
+
+        // headers can be chunked
+        if (concat_header_value) {
+            header_values[header_values.size() - 1] = header_values[header_values.size() - 1] + value;
+        }
+        else {
+            header_values.push_back(value);
+        }
+
+        concat_header_value = true;
+    }
+
+    size_t get_headers_length() {
+        return header_fields.size();
+    }
+
+    vector<string> get_headers_fields() {
+        return header_fields;
+    }
+
+    vector<string> get_headers_values() {
+        return header_values;
+    }
+
+    void set_body(string v) {
+        body = body + v;
+    }
+
+    string get_body() {
+        return body;
+    }
+
+private:
+    int status_code;
+    string status_message;
+
+    vector<string> header_fields;
+    vector<string> header_values;
+
+    bool concat_header_field;
+    bool concat_header_value;
+
+    string body;
+};
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/mbed-http/http_response_parser.h	Thu Feb 16 11:13:40 2017 +0100
@@ -0,0 +1,152 @@
+#ifndef _HTTP_RESPONSE_PARSER_H_
+#define _HTTP_RESPONSE_PARSER_H_
+
+#include "http_parser.h"
+#include "http_response.h"
+
+class HttpResponseParser {
+public:
+    HttpResponseParser(HttpResponse* a_response, Callback<void(const char *at, size_t length)> a_body_callback = 0)
+        : response(a_response), body_callback(a_body_callback)
+    {
+        settings = new http_parser_settings();
+
+        settings->on_message_begin = &HttpResponseParser::on_message_begin_callback;
+        settings->on_url = &HttpResponseParser::on_url_callback;
+        settings->on_status = &HttpResponseParser::on_status_callback;
+        settings->on_header_field = &HttpResponseParser::on_header_field_callback;
+        settings->on_header_value = &HttpResponseParser::on_header_value_callback;
+        settings->on_headers_complete = &HttpResponseParser::on_headers_complete_callback;
+        settings->on_chunk_header = &HttpResponseParser::on_chunk_header_callback;
+        settings->on_chunk_complete = &HttpResponseParser::on_chunk_complete_callback;
+        settings->on_body = &HttpResponseParser::on_body_callback;
+        settings->on_message_complete = &HttpResponseParser::on_message_complete_callback;
+
+        // Construct the http_parser object
+        parser = new http_parser();
+        http_parser_init(parser, HTTP_RESPONSE);
+        parser->data = (void*)this;
+    }
+
+    ~HttpResponseParser() {
+        if (parser) {
+            delete parser;
+        }
+        if (settings) {
+            delete settings;
+        }
+    }
+
+    size_t execute(const char* buffer, size_t buffer_size) {
+        return http_parser_execute(parser, settings, buffer, buffer_size);
+    }
+
+    void finish() {
+        http_parser_execute(parser, settings, NULL, 0);
+    }
+
+private:
+    // Member functions
+    int on_message_begin(http_parser* parser) {
+        return 0;
+    }
+
+    int on_url(http_parser* parser, const char *at, size_t length) {
+        return 0;
+    }
+
+    int on_status(http_parser* parser, const char *at, size_t length) {
+        string s(at, length);
+        response->set_status(parser->status_code, s);
+        return 0;
+    }
+
+    int on_header_field(http_parser* parser, const char *at, size_t length) {
+        string s(at, length);
+        response->set_header_field(s);
+        return 0;
+    }
+
+    int on_header_value(http_parser* parser, const char *at, size_t length) {
+        string s(at, length);
+        response->set_header_value(s);
+        return 0;
+    }
+
+    static int on_headers_complete(http_parser* parser) {
+        return 0;
+    }
+
+    int on_body(http_parser* parser, const char *at, size_t length) {
+        if (body_callback) {
+            body_callback(at, length);
+            return 0;
+        }
+
+        string s(at, length);
+        response->set_body(s);
+        return 0;
+    }
+
+    int on_message_complete(http_parser* parser) {
+        return 0;
+    }
+
+    int on_chunk_header(http_parser* parser) {
+        // ?? Don't know when this is used
+        return 0;
+    }
+
+    int on_chunk_complete(http_parser* parser) {
+        // ?? Don't know when this is used
+        return 0;
+    }
+
+    // Static http_parser callback functions
+    static int on_message_begin_callback(http_parser* parser) {
+        return ((HttpResponseParser*)parser->data)->on_message_begin(parser);
+    }
+
+    static int on_url_callback(http_parser* parser, const char *at, size_t length) {
+        return ((HttpResponseParser*)parser->data)->on_url(parser, at, length);
+    }
+
+    static int on_status_callback(http_parser* parser, const char *at, size_t length) {
+        return ((HttpResponseParser*)parser->data)->on_status(parser, at, length);
+    }
+
+    static int on_header_field_callback(http_parser* parser, const char *at, size_t length) {
+        return ((HttpResponseParser*)parser->data)->on_header_field(parser, at, length);
+    }
+
+    static int on_header_value_callback(http_parser* parser, const char *at, size_t length) {
+        return ((HttpResponseParser*)parser->data)->on_header_value(parser, at, length);
+    }
+
+    static int on_headers_complete_callback(http_parser* parser) {
+        return ((HttpResponseParser*)parser->data)->on_headers_complete(parser);
+    }
+
+    static int on_body_callback(http_parser* parser, const char *at, size_t length) {
+        return ((HttpResponseParser*)parser->data)->on_body(parser, at, length);
+    }
+
+    static int on_message_complete_callback(http_parser* parser) {
+        return ((HttpResponseParser*)parser->data)->on_message_complete(parser);
+    }
+
+    static int on_chunk_header_callback(http_parser* parser) {
+        return ((HttpResponseParser*)parser->data)->on_chunk_header(parser);
+    }
+
+    static int on_chunk_complete_callback(http_parser* parser) {
+        return ((HttpResponseParser*)parser->data)->on_chunk_complete_callback(parser);
+    }
+
+    HttpResponse* response;
+    Callback<void(const char *at, size_t length)> body_callback;
+    http_parser* parser;
+    http_parser_settings* settings;
+};
+
+#endif // _HTTP_RESPONSE_PARSER_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/mbed-http/https_request.h	Thu Feb 16 11:13:40 2017 +0100
@@ -0,0 +1,428 @@
+#ifndef _MBED_HTTPS_REQUEST_H_
+#define _MBED_HTTPS_REQUEST_H_
+
+/* Change to a number between 1 and 4 to debug the TLS connection */
+#define DEBUG_LEVEL 0
+
+#include <string>
+#include <vector>
+#include <map>
+#include "http_parser.h"
+#include "http_response.h"
+#include "http_request_builder.h"
+#include "http_response_parser.h"
+#include "http_parsed_url.h"
+
+#include "mbedtls/platform.h"
+#include "mbedtls/ssl.h"
+#include "mbedtls/entropy.h"
+#include "mbedtls/ctr_drbg.h"
+#include "mbedtls/error.h"
+
+#if DEBUG_LEVEL > 0
+#include "mbedtls/debug.h"
+#endif
+
+/**
+ * \brief HttpsRequest implements the logic for interacting with HTTPS servers.
+ */
+class HttpsRequest {
+public:
+    /**
+     * HttpsRequest Constructor
+     * Initializes the TCP socket, sets up event handlers and flags.
+     *
+     * @param[in] net_iface The network interface
+     * @param[in] ssl_ca_pem String containing the trusted CAs
+     * @param[in] method HTTP method to use
+     * @param[in] url URL to the resource
+     * @param[in] body_callback Callback on which to retrieve chunks of the response body.
+                                If not set, the complete body will be allocated on the HttpResponse object,
+                                which might use lots of memory.
+     */
+    HttpsRequest(NetworkInterface* net_iface,
+                 const char* ssl_ca_pem,
+                 http_method method,
+                 const char* url,
+                 Callback<void(const char *at, size_t length)> body_callback = 0)
+    {
+        _parsed_url = new ParsedUrl(url);
+        _body_callback = body_callback;
+        _tcpsocket = new TCPSocket(net_iface);
+        _request_builder = new HttpRequestBuilder(method, _parsed_url);
+        _response = NULL;
+        _debug = false;
+        _ssl_ca_pem = ssl_ca_pem;
+
+        DRBG_PERS = "mbed TLS helloword client";
+
+        mbedtls_entropy_init(&_entropy);
+        mbedtls_ctr_drbg_init(&_ctr_drbg);
+        mbedtls_x509_crt_init(&_cacert);
+        mbedtls_ssl_init(&_ssl);
+        mbedtls_ssl_config_init(&_ssl_conf);
+    }
+
+    /**
+     * HttpsRequest Destructor
+     */
+    ~HttpsRequest() {
+        mbedtls_entropy_free(&_entropy);
+        mbedtls_ctr_drbg_free(&_ctr_drbg);
+        mbedtls_x509_crt_free(&_cacert);
+        mbedtls_ssl_free(&_ssl);
+        mbedtls_ssl_config_free(&_ssl_conf);
+
+        if (_request_builder) {
+            delete _request_builder;
+        }
+
+        if (_tcpsocket) {
+            delete _tcpsocket;
+        }
+
+        if (_parsed_url) {
+            delete _parsed_url;
+        }
+
+        if (_response) {
+            delete _response;
+        }
+
+        // @todo: free DRBG_PERS ?
+    }
+
+    /**
+     * Execute the HTTPS request.
+     *
+     * @param[in] body Pointer to the request body
+     * @param[in] body_size Size of the request body
+     * @return An HttpResponse pointer on success, or NULL on failure.
+     *         See get_error() for the error code.
+     */
+    HttpResponse* send(const void* body = NULL, nsapi_size_t body_size = 0) {
+        /* Initialize the flags */
+        /*
+         * Initialize TLS-related stuf.
+         */
+        int ret;
+        if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
+                          (const unsigned char *) DRBG_PERS,
+                          sizeof (DRBG_PERS))) != 0) {
+            print_mbedtls_error("mbedtls_crt_drbg_init", ret);
+            _error = ret;
+            return NULL;
+        }
+
+        if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *)_ssl_ca_pem,
+                           strlen(_ssl_ca_pem) + 1)) != 0) {
+            print_mbedtls_error("mbedtls_x509_crt_parse", ret);
+            _error = ret;
+            return NULL;
+        }
+
+        if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf,
+                        MBEDTLS_SSL_IS_CLIENT,
+                        MBEDTLS_SSL_TRANSPORT_STREAM,
+                        MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
+            print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
+            _error = ret;
+            return NULL;
+        }
+
+        mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL);
+        mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg);
+
+        /* It is possible to disable authentication by passing
+         * MBEDTLS_SSL_VERIFY_NONE in the call to mbedtls_ssl_conf_authmode()
+         */
+        mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+
+#if DEBUG_LEVEL > 0
+        mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL);
+        mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL);
+        mbedtls_debug_set_threshold(DEBUG_LEVEL);
+#endif
+
+        if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) {
+            print_mbedtls_error("mbedtls_ssl_setup", ret);
+            _error = ret;
+            return NULL;
+        }
+
+        mbedtls_ssl_set_hostname(&_ssl, _parsed_url->host());
+
+        mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(_tcpsocket),
+                                   ssl_send, ssl_recv, NULL );
+
+        /* Connect to the server */
+        if (_debug) mbedtls_printf("Connecting to %s:%d\r\n", _parsed_url->host(), _parsed_url->port());
+        ret = _tcpsocket->connect(_parsed_url->host(), _parsed_url->port());
+        if (ret != NSAPI_ERROR_OK) {
+            if (_debug) mbedtls_printf("Failed to connect\r\n");
+            onError(_tcpsocket, -1);
+            return NULL;
+        }
+
+       /* Start the handshake, the rest will be done in onReceive() */
+        if (_debug) mbedtls_printf("Starting the TLS handshake...\r\n");
+        ret = mbedtls_ssl_handshake(&_ssl);
+        if (ret < 0) {
+            if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
+                ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
+                print_mbedtls_error("mbedtls_ssl_handshake", ret);
+                onError(_tcpsocket, -1);
+            }
+            else {
+                _error = ret;
+            }
+            return NULL;
+        }
+
+        char* request = _request_builder->build(body, body_size);
+        size_t request_size = strlen(request);
+
+        ret = mbedtls_ssl_write(&_ssl, (const unsigned char *) request, request_size);
+
+        free(request);
+
+        if (ret < 0) {
+            if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
+                ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
+                print_mbedtls_error("mbedtls_ssl_write", ret);
+                onError(_tcpsocket, -1 );
+            }
+            else {
+                _error = ret;
+            }
+            return NULL;
+        }
+
+        /* It also means the handshake is done, time to print info */
+        if (_debug) mbedtls_printf("TLS connection to %s:%d established\r\n", _parsed_url->host(), _parsed_url->port());
+
+        const uint32_t buf_size = 1024;
+        char *buf = new char[buf_size];
+        mbedtls_x509_crt_info(buf, buf_size, "\r    ",
+                        mbedtls_ssl_get_peer_cert(&_ssl));
+        if (_debug) mbedtls_printf("Server certificate:\r\n%s\r", buf);
+
+        uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
+        if( flags != 0 )
+        {
+            mbedtls_x509_crt_verify_info(buf, buf_size, "\r  ! ", flags);
+            if (_debug) mbedtls_printf("Certificate verification failed:\r\n%s\r\r\n", buf);
+        }
+        else {
+            if (_debug) mbedtls_printf("Certificate verification passed\r\n\r\n");
+        }
+
+        // Create a response object
+        _response = new HttpResponse();
+        // And a response parser
+        HttpResponseParser parser(_response, _body_callback);
+
+        // Set up a receive buffer (on the heap)
+        uint8_t* recv_buffer = (uint8_t*)malloc(HTTP_RECEIVE_BUFFER_SIZE);
+
+        /* Read data out of the socket */
+        while ((ret = mbedtls_ssl_read(&_ssl, (unsigned char *) recv_buffer, HTTP_RECEIVE_BUFFER_SIZE)) > 0) {
+            // Don't know if this is actually needed, but OK
+            size_t _bpos = static_cast<size_t>(ret);
+            recv_buffer[_bpos] = 0;
+
+            size_t nparsed = parser.execute((const char*)recv_buffer, _bpos);
+            if (nparsed != _bpos) {
+                print_mbedtls_error("parser_error", nparsed);
+                // parser error...
+                _error = -2101;
+                free(recv_buffer);
+                return NULL;
+            }
+            // No more chunks? break out of this loop
+            if (_bpos < HTTP_RECEIVE_BUFFER_SIZE) {
+                break;
+            }
+        }
+        if (ret < 0) {
+            if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
+                print_mbedtls_error("mbedtls_ssl_read", ret);
+                onError(_tcpsocket, -1 );
+            }
+            else {
+                _error = ret;
+            }
+            free(recv_buffer);
+            return NULL;
+        }
+
+        parser.finish();
+
+        _tcpsocket->close();
+        free(recv_buffer);
+
+        return _response;
+    }
+
+    /**
+     * Closes the TCP socket
+     */
+    void close() {
+        _tcpsocket->close();
+    }
+
+    /**
+     * Set a header for the request.
+     *
+     * The 'Host' and 'Content-Length' headers are set automatically.
+     * Setting the same header twice will overwrite the previous entry.
+     *
+     * @param[in] key Header key
+     * @param[in] value Header value
+     */
+    void set_header(string key, string value) {
+        _request_builder->set_header(key, value);
+    }
+
+    /**
+     * Get the error code.
+     *
+     * When send() fails, this error is set.
+     */
+    nsapi_error_t get_error() {
+        return _error;
+    }
+
+    /**
+     * Set the debug flag.
+     *
+     * If this flag is set, debug information from mbed TLS will be logged to stdout.
+     */
+    void set_debug(bool debug) {
+        _debug = debug;
+    }
+
+protected:
+    /**
+     * Helper for pretty-printing mbed TLS error codes
+     */
+    static void print_mbedtls_error(const char *name, int err) {
+        char buf[128];
+        mbedtls_strerror(err, buf, sizeof (buf));
+        mbedtls_printf("%s() failed: -0x%04x (%d): %s\r\n", name, -err, err, buf);
+    }
+
+#if DEBUG_LEVEL > 0
+    /**
+     * Debug callback for mbed TLS
+     * Just prints on the USB serial port
+     */
+    static void my_debug(void *ctx, int level, const char *file, int line,
+                         const char *str)
+    {
+        const char *p, *basename;
+        (void) ctx;
+
+        /* Extract basename from file */
+        for(p = basename = file; *p != '\0'; p++) {
+            if(*p == '/' || *p == '\\') {
+                basename = p + 1;
+            }
+        }
+
+        if (_debug) {
+            mbedtls_printf("%s:%04d: |%d| %s", basename, line, level, str);
+        }
+    }
+
+    /**
+     * Certificate verification callback for mbed TLS
+     * Here we only use it to display information on each cert in the chain
+     */
+    static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
+    {
+        const uint32_t buf_size = 1024;
+        char *buf = new char[buf_size];
+        (void) data;
+
+        if (_debug) mbedtls_printf("\nVerifying certificate at depth %d:\n", depth);
+        mbedtls_x509_crt_info(buf, buf_size - 1, "  ", crt);
+        if (_debug) mbedtls_printf("%s", buf);
+
+        if (*flags == 0)
+            if (_debug) mbedtls_printf("No verification issue for this certificate\n");
+        else
+        {
+            mbedtls_x509_crt_verify_info(buf, buf_size, "  ! ", *flags);
+            if (_debug) mbedtls_printf("%s\n", buf);
+        }
+
+        delete[] buf;
+        return 0;
+    }
+#endif
+
+    /**
+     * Receive callback for mbed TLS
+     */
+    static int ssl_recv(void *ctx, unsigned char *buf, size_t len) {
+        int recv = -1;
+        TCPSocket *socket = static_cast<TCPSocket *>(ctx);
+        recv = socket->recv(buf, len);
+
+        if (NSAPI_ERROR_WOULD_BLOCK == recv) {
+            return MBEDTLS_ERR_SSL_WANT_READ;
+        }
+        else if (recv < 0) {
+            return -1;
+        }
+        else {
+            return recv;
+        }
+   }
+
+    /**
+     * Send callback for mbed TLS
+     */
+    static int ssl_send(void *ctx, const unsigned char *buf, size_t len) {
+       int size = -1;
+        TCPSocket *socket = static_cast<TCPSocket *>(ctx);
+        size = socket->send(buf, len);
+
+        if(NSAPI_ERROR_WOULD_BLOCK == size) {
+            return len;
+        }
+        else if (size < 0){
+            return -1;
+        }
+        else {
+            return size;
+        }
+    }
+
+    void onError(TCPSocket *s, int error) {
+        s->close();
+        _error = error;
+    }
+
+protected:
+    TCPSocket* _tcpsocket;
+
+    Callback<void(const char *at, size_t length)> _body_callback;
+    ParsedUrl* _parsed_url;
+    HttpRequestBuilder* _request_builder;
+    HttpResponse* _response;
+    const char *DRBG_PERS;
+    const char *_ssl_ca_pem;
+
+    nsapi_error_t _error;
+    bool _debug;
+
+    mbedtls_entropy_context _entropy;
+    mbedtls_ctr_drbg_context _ctr_drbg;
+    mbedtls_x509_crt _cacert;
+    mbedtls_ssl_context _ssl;
+    mbedtls_ssl_config _ssl_conf;
+};
+
+#endif // _MBED_HTTPS_REQUEST_H_