POST 请求与 C++ curl

问题描述

我在我的服务器上尝试 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

指向的数据不会被库复制:因此,它 必须由调用应用程序保留,直到关联 转移完成。可以通过设置 CURLOPT_COPYPOSTFIELDS 选项来更改此行为(因此 libcurl 会复制数据)。

你还需要设置 CURLOPT_POSTFIELDSIZE 因为 CURLOPT_POSTFIELDS 只提供一个指针。

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