C++ C++;使用cURL+发布请求;JSON库

C++ C++;使用cURL+发布请求;JSON库,c++,json,c++11,curl,C++,Json,C++11,Curl,我想使用cURL执行POST请求。 我正在使用(github:nlohmann/json)库来处理我的json对象创建。我收到了http200响应,但是没有附加POST数据 在此行调用std::cout时: curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str()); dump()返回的字符串对象是临时的,在退出curl\u easy\u setopt()时会被销毁,从而在libCURL尝试发布JSON数据时,CUR

我想使用
cURL
执行
POST
请求。 我正在使用(github:nlohmann/json)库来处理我的
json
对象创建。我收到了
http200响应
,但是没有附加
POST
数据

在此行调用
std::cout时:

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str());
dump()
返回的字符串对象是临时的,在退出
curl\u easy\u setopt()
时会被销毁,从而在libCURL尝试发布JSON数据时,
CURLOPT\u POSTFIELDS
会留下一个悬空指针,该指针可能指向内存中的JSON数据,也可能不指向

根据:

库不会复制指向的数据:因此,调用应用程序必须保留该数据,直到相关传输完成。通过设置该选项,可以更改此行为(因此libcurl会复制数据)

因此,您需要:

  • CURLOPT\u POSTFIELDS
    更改为
    CURLOPT\u COPYPOSTFIELDS

    curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, json_data.dump().c_str());
    
  • json\u data.dump()
    的结果保存到一个局部变量,该局部变量在
    curl\u easy\u perform()
    退出之前不会超出范围:

    std::string json = json_data.dump();
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
    ...
    

谢谢。我会试试这个,然后再回来找你。你帮我节省了几个小时的测试时间,让我不会发疯。。。谢谢
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str());
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, json_data.dump().c_str());
std::string json = json_data.dump();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
...