C ++中的cURL POST请求

时间:2018-08-09 21:53:45

标签: c++ curl

我有cURL https请求,我正在尝试用C ++程序发送到我的Web服务器。我收到“错误请求”格式的回复。

CURL *curl;
CURLcode res;

curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl)
{
    int res = 0;
    snprintf(curl_url, sizeof(curl_url), "https://%s:8080/hello", results);
    snprintf(curl_fields, sizeof(curl_fields),"\"name\":\"%s\", \"key\":\"%s\"", name, data);


    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, "charsets: utf-8");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_URL, curl_url);
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, curl_fields);

    res = curl_easy_perform(curl);
    if ( res )
    {
        ---error---
    }
    curl_easy_cleanup(curl);
    curl_global_cleanup();
}

我可以寻求帮助吗?

1 个答案:

答案 0 :(得分:2)

您是否要发送以下json?

{
  "name": name,
  "data": data
}

从这行代码

  snprintf(curl_fields, sizeof(curl_fields),"\"name\":\"%s\", \"key\":\"%s\"", name, data);

那不是吗

  snprintf(curl_fields, sizeof(curl_fields),"{\"name\":\"%s\", \"key\":\"%s\"}", name, data);

(添加花括号)