Send post request



  • I'm wondering if it is possible send a post request maybe using some curl c++ library, has anyone tried?

    Maurzio



  • Hi @maurizio-pinzi yes you can do POST request starting with SDK 1.4

    I have introduced a new class called HttpPostClient, it still needs API reference docs. So I will introduce it briefly here.

    It works just like the GET based HttpClient. You provide an URL and some callback methods. Since you need to provide post data, you must also set a Content-Type header. I will show how, in a bit.

    There are 2 request body data callback functions you need to provide for HttpPostClient:

    • setBodyLengthCallback: A function you define that returns the byte length of the POST data
    • setBodyDataCallback: A function you define that actually provide the raw POST data

    In contrast to the HttpClient class, you need to call the method post() on HttpPostClient to execute the request.

    Here is an example - I assume you have already setup the network:

    // Construct the post request with URL and Content-type header
    postClient = mono::network::HttpPostClient("http://httpbin.org/post", "Content-Type: text/plain\r\n");
    
    // set the body length callback
    postClient.setBodyLengthCallback<AppController>(this, &AppController::provideLength);
    
    //set the body data provider callback
    postClient.setBodyDataCallback<AppController>(this, &AppController::provideData);
    
    // set the response data callback
    postClient.setDataReadyCallback<AppController>(this, &AppController::httpDone);
    
    // execute the request
    postClient.post();
    

    Notice that we set the raw header values in the constructor's second parameter. You must add a trailing \r\n to the header, if you do not the request will be invalid. You can add more header values in the second parameter, if you wish to. (Separated by \r\n)

    Here are the two body data callbacks:

    uint16_t AppController::provideLength()
    {
        return 5;
    }
    
    void AppController::provideData(char *data)
    {
        const char *postStr = "Hello"
        memcpy(data, postStr, strlen(postStr));
    }
    

    Hope this does the trick for you :-)


Log in to reply