I’m having trouble getting updates from my Telegram bot using a C++ Boost Beast HTTP client. The POST request works fine in Postman, but my code keeps getting a 400 Bad Request error.
Here’s what I’ve tried:
void sendRequest() {
std::string botToken = "mySecretToken123";
std::string host = "api.telegram.org";
std::string target = "/bot" + botToken + "/getUpdates";
http::request<http::string_body> req{http::verb::post, target, 11};
req.set(http::field::host, host);
req.set(http::field::user_agent, "MyBotClient/1.0");
req.set(http::field::content_type, "application/json");
req.body() = "";
req.prepare_payload();
// Send request and handle response...
}
I’ve also tried the SSL version using port 443, but I get the same error. The SSL handshake seems to work, though.
Any ideas what I’m doing wrong? Could it be a header issue or something with the request format? Thanks for any help!
I’ve encountered similar issues with the Telegram Bot API before. One thing that often gets overlooked is the Content-Length header. Even though your request body is empty, you should explicitly set it to 0. Try adding this line before prepare_payload():
req.set(http::field::content_length, “0”);
Also, make sure you’re using HTTPS, not HTTP. The Telegram API requires secure connections. If you’re still having trouble, enable verbose logging in Boost.Beast to see the full request and response details. This can help pinpoint where things are going wrong.
Lastly, verify that your bot token is active and has the necessary permissions. Sometimes tokens can expire or be revoked without notice.
I’ve dealt with similar Telegram Bot API issues, and there are a few things to consider. First, ensure you’re using HTTPS, as Telegram mandates secure connections. Your code snippet doesn’t show the connection setup, so double-check that.
Another often overlooked aspect is proper URL encoding of the bot token in the target path. Some tokens contain special characters that need encoding. Try using a URL encoding function on your botToken before constructing the target string.
Also, Telegram’s API can be picky about empty request bodies. Instead of an empty string, try setting the body to ‘{}’ to represent an empty JSON object:
req.body() = “{}”;
If these don’t resolve the issue, enable detailed logging in Boost.Beast to inspect the full request and response. This can provide valuable clues about what’s causing the 400 error.
hey there, have u tried adding a timeout to ur request? sometimes the api can be slow. also, double-check ur botToken - even a tiny typo can cause a 400 error. maybe try printing the full request before sending to make sure everythings correct?