c++ - 使用 C++curl 进行 POST 请求

标签 c++ libcurl

我在我的服务器上尝试 POST JSON,但它不起作用。当我发布时,服务器是空的并且没有文件。

如何正确POST?

CURL *curl;
    string data;
    CURLcode res;
    std::ifstream myfile;
    myfile.open("test_4.json");
    string content( (istreambuf_iterator<char>(myfile) ),
                  (istreambuf_iterator<char>()    ) );
    curl = curl_easy_init();
    string l="filedata=";
    if(curl) {

    curl_easy_setopt(curl, CURLOPT_URL, "my_server");

    
     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, l+content);

 
    res = curl_easy_perform(curl);
 
    curl_easy_cleanup(curl);
  }

我还有 python 代码可以运行

pp=requests.post("my_server",data={"filedata":response})

我的服务器上的 POST js 代码(我无法更改)

app.post("/api/arch_base",jsonParser,function(req,res){
    
    if(!req.body) return res.sendStatus(400);
    
    const fdata=req.body.filedata;
    
    console.log(fdata);
    
     const collection = req.app.locals.collection;
    
    collection.find({}).toArray(function(err,arch_data){
         if(err) return console.log(err);
         
         if(arch_data.length>0)
         {
             let id=arch_data[0]._id;
             
             collection.findOneAndUpdate({_id:id},{$set: {FileData:fdata}},{returnOriginal:false},function(err,result){
                 
                  if(err) return console.log(err);
             });
         }
         
        
      });
    
    
    haveUpdates=true;
    
    
});

最佳答案

libcurl 是 C 语言,而不是 C++。它需要 char*,而不是 std::string

同样来自https://curl.se/libcurl/c/CURLOPT_POSTFIELDS.html :

The data pointed to is NOT copied by the library: as a consequence, it must be preserved by the calling application until the associated transfer finishes. This behavior can be changed (so libcurl does copy the data) by setting the CURLOPT_COPYPOSTFIELDS option.

您还需要设置 CURLOPT_POSTFIELDSIZE,因为 CURLOPT_POSTFIELDS 仅提供指针。

另外,我确定您得到的是“filedata=”,而不是“data={filedata:}”。您可能需要一个 json 库(例如 jsoncpp)来确保您获得有效的 json。

关于c++ - 使用 C++curl 进行 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68225219/

相关文章:

C++ CURL Json 请求不一致 API 以进行消息发布

c++ - 使用 libcurl 创建 InfluxDB 数据库的 HTTP post

c++ - C++ 中的 upper_bound/lower_bound 函数

xml - libcurl SSL证书验证

C++:使用 libcurl 和流

c++ - 创建线程总是对性能有好处吗?

c++ - 打印 curl 请求

c++ - VirtualQueryEx 错误 - 页面太多

c++ - 用非纯虚版本重载纯虚函数

c++ - Android NDK C++ 代码的内存调试工具