nab*_*yan 7 c c++ json curl libcurl
我正在尝试通过C++的curl库做一些请求.我可以成功地执行我的请求并通过命令行获得正确的响应,但我无法通过C++代码获得正确的响应.我的命令行命令如下所示
curl -X POST -H 'Accept: application/json' -H 'Content-Type: application/json' -H 'Authorization: <some_hash_value>' -k <my_full_url> -data '<my_json_string>'
Run Code Online (Sandbox Code Playgroud)
这很好.现在我尝试用C++代码做同样的请求.我的代码看起来像这样
void performRequest(const std::string& json, const void* userData, CallbackFunction callback)
{
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, (std::string("Authorization: ") + m_authorization).c_str());
CURL* curlHandle = curl_easy_init();
if (!curlHandle)
{
std::cerr << "Curl handler initialization failed";
}
curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, headers);
// specify target URL, and note that this URL should include a file name, not only a directory
curl_easy_setopt(curlHandle, CURLOPT_URL, m_url.c_str());
// enable uploading
curl_easy_setopt(curlHandle, CURLOPT_UPLOAD, 1L);
// set HTTP method to POST
curl_easy_setopt(curlHandle, CURLOPT_CUSTOMREQUEST, "POST");
// set json data; I use EXACTLY the same string as in command line
curl_easy_setopt(curlHandle, CURLOPT_COPYPOSTFIELDS, json.c_str());
// set data size
curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDSIZE_LARGE, json.size());
// set user data for getting it in response
curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, userData); // pointer to a custom struct
// set callback function for getting response
curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, callback); // some callback
// send request
curl_easy_perform(curlHandle);
curl_easy_cleanup(curlHandle);
curl_slist_free_all(headers);
}
Run Code Online (Sandbox Code Playgroud)
但是,出于某种原因,我从服务器的响应中得到一个错误,从中我可以假设我的代码的请求不等于命令行的命令.似乎身体没有发送.当我使用CURLOPT_DEBUGFUNCTION转储调试信息时,我无法看到我的请求Json正文.
这里有什么问题?我究竟做错了什么?有任何想法吗?
CURLOPT_CUSTOMREQUEST,CURLOPT_UPLOAD和CURLOPT_NOSIGNAL设置语句,因为不需要它们。CURLOPT_POSTFIELDSIZE_LARGE,尽管如果在设置之前设置它可以正常工作CURLOPT_COPYPOSTFIELDS。如果之前未设置大小CURLOPT_COPYPOSTFIELDS,则假定数据是以零结尾的字符串;否则,存储的大小会通知库要复制的字节数。在任何情况下,尺寸不得在 后更改CURLOPT_COPYPOSTFIELDS,除非发出另一个CURLOPT_POSTFIELDS或选项。CURLOPT_COPYPOSTFIELDS(参见:curl.haxx.se/libcurl/c/CURLOPT_COPYPOSTFIELDS.html)