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

Can't send complex POST request with begin/endRequest #178

Open
kaysond opened this issue Aug 7, 2024 · 2 comments
Open

Can't send complex POST request with begin/endRequest #178

kaysond opened this issue Aug 7, 2024 · 2 comments
Labels
type: imperfection Perceived defect in any part of project

Comments

@kaysond
Copy link

kaysond commented Aug 7, 2024

My code looks roughly like:

char json_string[512];
int length = mylib.sprint_json(json_string);
Serial.println("Sending JSON:");
Serial.println(json_string);
Serial.print("Length: ");
Serial.println(length);

client.beginRequest();
client.post("/");
client.sendHeader("Host", "my.hostname.tld");
client.sendHeader("Content-Type", "application/json");
client.sendHeader("Content-Length", length);
client.beginBody();
client.print(json_string);
client.endRequest();
int statusCode = client.responseStatusCode();
String response = client.responseBody();

mylib.sprint_json is essentially an sprintf() wrapper.

This doesn't work. The request never goes out.

If I change the post request to:

client.post("/", "application/json", json_string);

it works just fine.

Am I doing something wrong? I copied the example. From the Serial.println()s, I can see that the string and length are correct...

@per1234 per1234 added the type: imperfection Perceived defect in any part of project label Aug 7, 2024
@jonasbarsten
Copy link

Did some testing and it seems complex POST requests only work with json strings shorter than 504 characters.

@jonasbarsten
Copy link

I solved it like this for now:

  String input = "suuuuuuuper-loooooooooooooooong-striiiiiiiiiiiing";
  const size_t contentLength = input.length();

  client.beginRequest();
  client.post(path);
  client.sendHeader("Content-Type", "application/json");
  client.sendHeader("Content-Length", contentLength);
  client.beginBody();

  constexpr size_t chunkSize = 64;

  for (size_t i = 0; i < contentLength; i = i + chunkSize) {
    if (contentLength - i < chunkSize) {
      String chunk = input.substring(i);
      client.print(chunk);
    } else {
      String chunk = input.substring(i, chunkSize + i);
      client.print(chunk);
    }
  }

  client.endRequest();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: imperfection Perceived defect in any part of project
Projects
None yet
Development

No branches or pull requests

3 participants