POST 使用 C++ curl 请求

POST request with C++ curl

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

如何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-library(例如 jsoncpp)以确保您获得有效的 json.