【问题标题】:C++ Telegram Bot POST request for updates no resultC++ Telegram Bot POST 更新请求无结果
【发布时间】:2020-08-11 09:42:33
【问题描述】:

我正在尝试创建一个电报机器人。我首先尝试使用 /getUpdates 方法从 bot 获取更新,就像 Telegram API 中所说的那样。 使用 Postman,请求运行良好,我拥有 json 格式的所有数据。 使用 cUrl 我没有响应,res 为 0。这是代码的 sn-p:

#include <iostream>
#include <curl/curl.h>
#include <string>

using namespace std;

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}


void getUpdates()
{
    std::string readBuffer;

    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if(curl) {
      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
      curl_easy_setopt(curl, CURLOPT_URL, "http://api.telegram.org/BOTTOKEN/getUpdates");
      curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
      curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
      struct curl_slist *headers = NULL;
      curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
      curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
      std::cout << "Buffer content"<<readBuffer << std::endl;
      long code = -1;
      curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &code );
      std::cout<<"HTTP Response Code: "<< code <<std::endl;
      std::cout<<"Res: "<<res<<std::endl;
      res = curl_easy_perform(curl);

    }
}

int main()
{
    getUpdates();
    return 0;
}

缓冲区内容为空,res为0。

你能给我一些提示吗?谢谢!

【问题讨论】:

    标签: c++ curl bots telegram


    【解决方案1】:

    我解决了!这是更新的代码:

    void getUpdates()
    {
        CURL *curl;
        CURLcode res;
        curl = curl_easy_init();
        if(curl) {
          curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
          curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
          curl_easy_setopt(curl, CURLOPT_URL, "http://api.telegram.org/botyourtoken/getUpdates");
          curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
          curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
          struct curl_slist *headers = NULL;
          curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
          curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
          curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
          std::string readBuffer;
          curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
          res = curl_easy_perform(curl);
          std::cout << "Buffer content: "<<std::endl;
          std::cout<<readBuffer << std::endl;
        }
        curl_easy_cleanup(curl);
    }
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 2018-06-13
      • 2016-10-23
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多