繁体   English   中英

使用 C++ curl POST 请求

[英]POST request with 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=<file>”,而不是“data={filedata:<file>}”。 您可能需要一个 json-library(例如 jsoncpp)来确保您获得有效的 json。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM