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

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

本文关键字:数据 请求 二进制 post protobuf HTTP 何通过 curl 调用 C++      更新时间:2023-10-16

我正在尝试在带有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);设置数据大小。

你可以在那里找到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: %sn",
curl_easy_strerror(res));
/* always cleanup */ 
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}

修复您的原始建议可能会使其如下所示(基于 libcurl 网站的 simplepost 示例(:

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