C++:如何通过 curl 调用使用 HTTP post 请求发送二进制数据(protobuf 数据)

标签 c++ curl protocol-buffers libcurl

我正在尝试使用 protobuf 数据在 url 上发出 POST 请求。我不知道如何/在哪里添加二进制数据。下面是我的 C++ 程序。 "

void sendContent()
{
    using namespace std;
    int Error = 0;
    //CString str;

    CURL* curl;
    CURLcode res;

    struct curl_slist *headerlist = NULL;
    curl_global_init(CURL_GLOBAL_ALL);

    curl = curl_easy_init();

    headerlist = curl_slist_append(headerlist, "Content-Type: application/x-protobuf");

    //Set URL to recevie POST
    curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
    curl_easy_setopt(curl, CURLOPT_POST, true);
    curl_easy_setopt(curl, CURLOPT_HEADER, true);
    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:9090/info");  
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);
    curl_global_cleanup();

}"

最佳答案

您应该通过curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);设置数据指针。同时,您应该通过curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, length_of_data);设置数据大小

您可以在 there 中找到 libcurl 发布示例.

然后我复制下面的程序。

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
  CURL *curl;
  CURLcode res;

  /* In windows, this will init the winsock stuff */ 
  curl_global_init(CURL_GLOBAL_ALL);

  /* get a curl handle */ 
  curl = curl_easy_init();
  if(curl) {
    /* First set the URL that is about to receive our POST. This URL can
       just as well be a https:// URL if that is what should receive the
       data. */ 
    curl_easy_setopt(curl, CURLOPT_URL, "http://postit.example.com/moo.cgi");
    /* Now specify the POST data */
    /* size of the POST data */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, length_of_data);
    /* binary data */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

    /* Perform the request, res will get the return code */ 
    res = curl_easy_perform(curl);
    /* Check for errors */ 
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* always cleanup */ 
    curl_easy_cleanup(curl);
  }
  curl_global_cleanup();
  return 0;
}

关于C++:如何通过 curl 调用使用 HTTP post 请求发送二进制数据(protobuf 数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59045074/

相关文章:

c++ - AMD 的 NVML 对应物 (c++)

php - session 数据的 file_get_contents(或 curl 或 fopen)问题

elasticsearch - 通过 cURL/Postman 向 Elastic APM 发送手动 OTLP/HTTP (opentelemetry) 请求

c++ - 如何交换二维数组的最大和最小成员索引

C++ CTreeCtrl,如何仅编辑树的一项

c++ - 如何存储从 std::bind 返回的可调用对象以获取指向成员函数的指针?

batch-file - 遍历批处理文件中的一堆 url

java - Python 的 urllib2.urlopen() 挂起与 Java ReSTLet 服务器的本地连接

go - 使用 dep 时如何正确包含协议(protocol)的 golang protobuf/ptypes?

c++ - 如何在 C++ 中从 protobuf 时间戳重建日期