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

9.9k views Asked by At

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?

2

There are 2 answers

2
gre_gor On BEST ANSWER

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.

0
Maximilian Gerhardt On

The header of such an authorization must look like (Wikipedia):

Authorization: Basic d2lraTpwZWRpYQ==

In short, you're probably just missing the "Basic" part. And need do change your code to

http.addHeader("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=");