ArduinoHttpClient
ArduinoHttpClient copied to clipboard
Getting 401 Errors with PUT But Getting 200 with GET
So I'm making requests to a server that requires an Authorisation header.
I can successfully call the GET endpoints setting the auth header.
GET REQUEST
client.beginRequest();
client.get("/api/v1/myGetRequest");
client.sendHeader("Authorization", "Basic abc123");
client.endRequest();
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("GET Status code: ");
Serial.println(statusCode);
Serial.print("GET Response: ");
Serial.println(response);
When I attempt a PUT request however I get a 401 status
PUT REQUEST
void postStatus() {
String postData;
Serial.println("making POST request");
if (alarmIsOn == true) {
postData = "{\"status\":\"alarmOn\"}";
} else {
postData = "{\"status\":\"alarmOff\"}";
}
String contentType = "application/json";
client.beginRequest();
client.put("/api/v1/myPutRequest", contentType, postData);
client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, postData.length());
client.sendHeader("Authorization", "Basic abc123");
client.sendHeader("accept", "application/json");
client.endRequest();
client.print(postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
}
I've verified that the auth token is correct using postman. Could somebody help me figure out why setting the auth header for GET works fine but doesnt work for PUT?
For anybody else that comes lands here from google, the correct way to write the PUT request is
putClient.beginRequest();
putClient.put(endpoint);
putClient.sendHeader("Content-Type", "application/json");
putClient.sendHeader("Authorization", "Basic abc");
putClient.sendHeader("Content-Length", String(jsonString.length()));
putClient.beginBody();
putClient.print(jsonString);
putClient.endRequest();