Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST to a RESTful API on an ESP8266 using authentication?

I can enter this URL from a browser, and after entering my credentials this successfully calls my API http://172.16.0.40/rest/vars/set/1/12/666.

I'm trying to do this from an an ESP8266 using HTTPClient. My credentials are username:password, and I used an online conversion utility to get dXNlcm5hbWU6cGFzc3dvcmQ=.

When executed, the following returns error 701 (no idea what that is).

HTTPClient http;
http.begin("172.16.0.40", 80, "/");
http.addHeader("Content-Type", "text/plain");
http.addHeader("Authorization", "dXNlcm5hbWU6cGFzc3dvcmQ=");
auto httpCode = http.POST("rest/vars/set/1/12/999");

If I comment out the Authorization header, I get a 401, which is unauthorized access. What am I doing wrong?

like image 543
WhiskerBiscuit Avatar asked Jan 04 '23 22:01

WhiskerBiscuit


1 Answers

You are trying to do a POST request to http://172.16.0.40/ with rest/vars/set/1/12/999 as payload.

HTTP status code 701 is not a standard code and is probably server specific.

You probably meant to do:

HTTPClient http;
http.begin("172.16.0.40", 80, "/rest/vars/set/1/12/999");
http.addHeader("Content-Type", "text/plain");
http.addHeader("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=");
auto httpCode = http.POST(payload);

If you want a GET request, call http.GET() instead of http.POST(payload) and you should get the same response as inside the browser.

Edit:
And as @MaximilianGerhardt already answered, you need to prepend Basic to your Authorization header.

like image 146
gre_gor Avatar answered Jan 13 '23 14:01

gre_gor