使用 libcurl C++ 发送 POST 请求。我几乎尝试了所有组合,除了我无法弄清楚的正确组合。
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE); /*Not Recommended to use but since certificates are not available this is a workaround added*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, FALSE); /*Not Recommended to use but since certificates are not available this is a workaround added*/
curl_easy_setopt(curl, CURLOPT_HTTPPOST, TRUE); //CURLOPT_POST does not work as well
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sJson);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, bytesCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, bytesCallback);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headBuffer);
Run Code Online (Sandbox Code Playgroud)
sJson是 a std::string,其主体由 所创建pb2json。
我不明白为什么尸体没有被发送?如果是 libcurl,我是否缺少一些 API,任何线索都值得赞赏!
我更喜欢使用自定义请求,下面CURLOPT_CUSTOMREQUEST是运行良好的代码片段!当您使用自定义请求时,没有任何暗示,您必须显式定义CURLOPT_HTTPHEADER
此处使用列表,为了简洁起见,我在这里使用了最少的代码。
此外,当您将sJson其作为c type stringusing传递c_str()并记住在传递内容长度(我最初不知何故错过了)时使用 +1 时,就像在 C 中一样,字符串只是char数组,按照惯例,它们以字节结尾NULL。
struct curl_slist* slist = NULL;
slist = curl_slist_append(slist, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sJson.c_str()); /* data goes here */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sJson.length() + 1); /* data goes here */
Run Code Online (Sandbox Code Playgroud)
编辑:使用curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");可能会在重定向中产生问题,请根据您的用例使用它。
| 归档时间: |
|
| 查看次数: |
4204 次 |
| 最近记录: |