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

C++: How can I Send binary data(protobuf data) using HTTP post request through a curl call

我正在尝试使用 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 post 示例。

然后我复制下面的程序。

#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;
}

修正你最初的建议可能会变成这样(基于来自 libcurl 网站的 the simplepost example):

#include <curl/curl.h>

int binarypost(char *binaryptr, long binarysize)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  struct curl_slist *headerlist = NULL;
  headerlist = curl_slist_append(headerlist, "Content-Type: application/x-protobuf");

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:9090/info");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, binaryptr);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, binarysize);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

    res = curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return (int)res;
}