Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting 401 Errors with PUT But Getting 200 with GET #151

Open
BarryDuggan opened this issue Apr 4, 2023 · 1 comment
Open

Getting 401 Errors with PUT But Getting 200 with GET #151

BarryDuggan opened this issue Apr 4, 2023 · 1 comment

Comments

@BarryDuggan
Copy link

BarryDuggan commented Apr 4, 2023

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?

@BarryDuggan
Copy link
Author

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();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant