1

I am trying to do a HTTPS post on ESP8266 as shown in Postman below

picture from Postman

But I keep getting: 'HTTP/1.1 401 Unauthorized'.

Can someone please help me with how to build up the headers correctly in the HTTPS POST? And maybe also give a link to some documentation? I cant seem to find any...

My code is:

const char* host = "api.dgs.com";
const int httpsPort = 443;
String url = "/ccs-int/v1/applicationdatalogging/1.0";
String msg = "";

WiFiClientSecure client;

Serial.print("connecting to : '");
Serial.print(host);
Serial.println("'");
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);

client.connect(host, httpsPort);

Serial.print("requesting URL: '");
Serial.print(url);
Serial.println("'");

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n" +
    "Content-Type: application/json" +
    "Authorization: Bearer " + authorization_code + "\r\n" +
    "Content-Length: " + msg.length() + "\r\n" +
    "\r\n" +
    msg + "\r\n");

Serial.println("request sent");
unsigned long timeout = millis();
while (client.available() == 0) {
    if (millis() - timeout > 5000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
    }
}
5
  • Unauthorized says it all. I can't see anything for authorization in your code
    – Martynas
    Apr 11, 2019 at 13:15
  • And the documentation you've asked httpstatuses.com/401
    – Martynas
    Apr 11, 2019 at 13:22
  • If you're getting to the point that you get a 401 back, HTTPS is succeeding. 'Unauthorized' should mean that there's an issue with your authorization code. Do you have access to a computer that can run curl? If you do, try doing this post from that. It would be something like curl -X POST --header "Authorization: Bearer AUTHCODE" --header "Content-Length: 0" https://api.dgs.com/ccs-int/v1/applicationdatalogging/1.0 replacing AUTHCODE with your authorization code. This may help you debug what's going on with it.
    – romkey
    Apr 11, 2019 at 15:13
  • I moved the autorization part up earlier in the 'client.print', which fixed the problem. However now I get a 411 error (Content-length has to be specified). Any idea what might be my new problem? I have specified the content length and I have also tried different values with no success.
    – T.Krebs
    May 9, 2019 at 12:40
  • @T.Krebs...can you share the full code example, It's a bit difficult to figure out which portion is setup and which is loop.
    – Amin Baig
    Mar 9, 2021 at 15:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.