我正试图通过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>'
效果很好。现在,我尝试在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);
}
但是,由于某些原因,我从服务器获得了响应中的错误,由此可以假设代码的请求与命令行的命令不等效。身体似乎不是被送去的。当我使用CURLOPT_DEBUGFUNCTION来转储调试信息时,我无法看到我的请求Json主体。
这里有什么问题?我做错了什么?有什么想法吗?
发布于 2016-04-25 15:35:09
CURLOPT_CUSTOMREQUEST
、CURLOPT_UPLOAD
和CURLOPT_NOSIGNAL
设置语句,因为它们不需要它们。CURLOPT_POSTFIELDSIZE_LARGE
的行,但如果在设置CURLOPT_COPYPOSTFIELDS
之前设置它,它可以正常工作。如果未在CURLOPT_COPYPOSTFIELDS
之前设置大小,则假定数据为以零结尾的字符串;否则存储的大小将通知库要复制的字节计数。在任何情况下,除非发出了另一个CURLOPT_COPYPOSTFIELDS
或CURLOPT_COPYPOSTFIELDS
选项,否则不能在CURLOPT_POSTFIELDS
之后更改大小。(见:COPYPOSTFIELDS.html发布于 2016-04-26 08:48:10
在windows中,您必须插入具有以下功能的winsock组件。
curl_global_init(CURL_GLOBAL_ALL);
https://stackoverflow.com/questions/36695400
复制相似问题