QuickSpot / walter-arduino

This repository contains all libraries and software to use Walter in the Arduino framework
Other
14 stars 3 forks source link

Looking for a working sample code for how to send HTTP POST requests. #11

Closed vt-vaio closed 9 months ago

vt-vaio commented 9 months ago

I need to send a post request via HTTP with JSON in the request body. I was trying to use httpSend() but always getting a 400 response from the backend. For me it looks like that JSON string is never transmitted as part of the request. I can reproduce the same 400 error with Postman when removing the JSON string from the body.

Below is a code snipped from my tests (the backend and API endpoints are replaced with placeholders).

    if(m_modem->httpConfigProfile(1, "my-backend")) {
        debug_out("Successfully configured the http profile");
    } 
    else {
        debug_out("Failed to configure HTTP profile");
        return;
    }

    std::string smsg = "{'id':'240ac4c6f33c','fw_version':'3.0'}";
    const uint8_t *msg = reinterpret_cast<const uint8_t*>(smsg.c_str());

    bool sent = m_modem->httpSend(1, "/my-endpoint", (uint8_t *) msg, sizeof(msg), WALTER_MODEM_HTTP_SEND_CMD_POST, WALTER_MODEM_HTTP_POST_PARAM_JSON);

    if(sent) {
        debug_out("Request successfully sent");

        delay(5000);

        debug_out("Looking for reply");

        WalterModemRsp *rsp = new WalterModemRsp();

        uint8_t incomingBuf[256] = { 0 };

        while(m_modem->httpDidRing(1, incomingBuf, sizeof(incomingBuf), rsp)) {
            esp_task_wdt_reset();
            debug_out("HTTP status code: " + String(rsp->data.httpResponse.httpStatus));
            Serial.printf("[%s]\r\n", incomingBuf);
        }

        debug_out("Stooped looking for reply");
    } 

Below is some debug output

TX: AT+SQNHTTPCFG=1,"my-backend",80,0,"","" RX: OK TX: AT+SQNHTTPSND=1,0,"/my-endpoint",4,"4" RX: > RX: OK RX: +SQNHTTPRING: 1,400,"text/html; charset=UTF-8",0 TX: AT+SQNHTTPRCV=1 RX: +CME ERROR: 587 TX: AT+SQNHTTPRCV=1 RX: +CME ERROR: 587 TX: AT+SQNHTTPRCV=1 RX: +CME ERROR: 587

vt-vaio commented 9 months ago

I've sorted the issue. My problem was in the the 4th parameter (dataSize). The sizeof always returned 4. By changing the code in the following way all works now.

    std::string smsg = "{'id':'240ac4c6f33c','fw_version':'3.0'}";
    const uint8_t *msg = reinterpret_cast<const uint8_t*>(smsg.c_str());

    bool sent = m_modem->httpSend(1, "/my-endpoint", (uint8_t *) msg, smsg.length(), WALTER_MODEM_HTTP_SEND_CMD_POST, WALTER_MODEM_HTTP_POST_PARAM_JSON);
vt-vaio commented 9 months ago

Solved, please see my previous comment for solution. Thank you.