Page 1 of 1

ESP32 http post request using Authorization Bearer

Posted: Wed May 11, 2022 6:17 am
by sohaibqamar86
Hi,
I am trying to make an HTTP Post request using Arduino for ESP32. I am using the HTTPClient library to make the Post request in which I have to use the Authorization Bearer token. Below is my code.

Code: Select all

//Your Domain name with URL path or IP address with path
const char* serverName = "http://domain.com";

void loop() {
    //Send an HTTP POST request every 10 minutes
    if ((millis() - lastTime) > timerDelay) {
        //Check WiFi connection status
        if(WiFi.status()== WL_CONNECTED){
            WiFiClient client;
            HTTPClient http;

            // Your Domain name with URL path or IP address with path
            http.begin(client, serverName);
            
            // Specify content-type header
	   //http.addHeader("Content-Type", "text/plain");
            //http.addHeader("Content-Type", "application/x-www-form-urlencoded");
	   // Specify Authorization-type header
            http.addHeader("Authorization", "Bearer eyJ0eXAiOiJK...");
            // Data to send with HTTP POST
            String httpRequestData = "/api/v1/cattle/location?cattle_id=1&location_date=2022-05-1015:25:00&latitude=12.1231111&longitude=-151.82723";
            // Send HTTP POST request
            int httpResponseCode = http.POST(httpRequestData);

            Serial.print("HTTP Response code: ");
            Serial.println(httpResponseCode);

            // Free resources
            http.end();
        }
        else {
            Serial.println("WiFi Disconnected");
        }
        lastTime = millis();
    }
}
I have tried both Content-Type and even without any Content-Type.
My ESP32 is successfully connecting and getting a valid IP Address. After making the Post request, I am getting
HTTP Response code: 400
.


I have checked the same Post request using Postman and I am getting the right response. Details of Postman's request are below.
testHTTP.png
testHTTP.png (74.21 KiB) Viewed 7724 times
Looking for advice to make it work, maybe it's trivial for experts.
Regards
Sohaib

Re: ESP32 http post request using Authorization Bearer

Posted: Wed May 11, 2022 3:49 pm
by lbernstone
Perhaps the token needs to be base64 encoded before sending?
There is authentication functionality included in the HTTPClient library. You call setAuthorization and setAuthorizationType (Bearer in this case), after begin, but before POST. It will handle the base64 translation.

Re: ESP32 http post request using Authorization Bearer

Posted: Sat Jun 11, 2022 8:26 am
by sohaibqamar86
Problem solved.
Below is the updated code. Hope it will save someone's time.

Code: Select all

#include <WiFi.h>
#include <HTTPClient.h>

#define TIME_POST_DATA 5000	// In miliSec

const char* ssid = "mySSID";
const char* password = "myPass";

//Your Domain name with URL path or IP address with path
const char* serverName2 = "http://domain.com/api/v1/cattle/location?cattle_id=1&location_date=2022-05-10%2015:25:00&latitude=12.1231111&longitude=-151.82723";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;


String payload;
int httpResponseCode;
String httpRequestData;

void setup() {
    Serial.begin(115200);

    WiFi.begin(ssid, password);
    Serial.println("Connecting");
    while(WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to WiFi network with IP Address: ");
    Serial.println(WiFi.localIP());
}

void loop() {
    //Send an HTTP POST request every 10 minutes
    if ((millis() - lastTime) > TIME_POST_DATA) {
        //Check WiFi connection status
        if(WiFi.status()== WL_CONNECTED){
            WiFiClient client;
            HTTPClient http;
			String recv_token = "eyJ0eXAiOiJK..."; // Complete Bearer token
			recv_token = "Bearer " + recv_token;	// Adding "Bearer " before token
			
			// Sending POST request for Location Data.
			http.begin(client, serverName2);
			http.addHeader("Authorization", recv_token); // Adding Bearer token as HTTP header
			httpRequestData = "http://domain.com/api/v1/cattle/location?cattle_id=1&location_date=2022-05-10%2015:25:00&latitude=12.1231111&longitude=-151.82723 HTTP/1.1";
			// Send HTTP POST request
            httpResponseCode = http.POST(httpRequestData);
            Serial.print("HTTP Response code: ");
            Serial.println(httpResponseCode);
            
            if (httpResponseCode>0) {
                payload = http.getString();
                Serial.println(payload);
            }
			// Free resources
            http.end();
			//while(1);
        }
        else {
            Serial.println("WiFi Disconnected");
        }
        lastTime = millis();
    }
}