【问题标题】:cURL POST request in C++C++ 中的 cURL POST 请求
【发布时间】:2019-01-17 11:07:42
【问题描述】:

我有 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, "charset: 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();
}

我能得到一些帮助吗?

【问题讨论】:

  • curl_url是什么类型?
  • 在使用它们之前尝试打印出这些值(如您的 URL)以确保它们是正确的。
  • char[256] 用于 curl_url 和 curl_fields。
  • 我注意到有时服务器需要User-Agent 标头。
  • charsets 不是有效的 HTTP 请求标头。也许你的意思是Accept-Charset

标签: c++ curl


【解决方案1】:

您是否尝试发送以下 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);

(添加花括号)

【讨论】:

  • 我可以试试。但是我读到设置标题会使用花括号格式化 json。不对吗?
  • 试试看然后回复我,我不认为是这样。
  • 我会这样做的。
  • 是的,你必须自己包含花括号,curl 不会为你做。此外,如果您使用 C++11 或更高版本,您可能会考虑使用 Raw string literal 使格式字符串更易于阅读:snprintf(curl_fields, sizeof(curl_fields), R"({"name":"%s", "key":"%s"})", name, data);
  • @RemyLebeau - 这是我在终端中运行的 curl 命令,我正在尝试在我的 C++ 程序中编写代码来发出该 curl 请求。我得到一个“错误的请求 400”输出。好像垃圾被送过来了。 curl --header "Content-Type: application/json" \--request POST \--data '{"key_info": {"john":"4x"}}' \xxx.xx.xx.xx:8080/hello ...你能帮忙吗我的 C++ 代码出来了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
相关资源
最近更新 更多