c++ - 内容类型 : application/x-www-form-urlencoded in curl

标签 c++ curl libcurl

我正在尝试编写一个c++程序,它使用curl库在Re​​d Hat Enterprise Virtualizatio(RHEV)上执行操作(创建VM等)。我正在使用 CURL 处理程序来执行后操作(创建 VM)。

CURL *curl;

struct curl_slist *headers=NULL; // init to NULL is important

curl_slist_append(headers, "Accept: application/xml");
curl_slist_append( headers, "Content-Type: application/xml");

/* get a curl handle */
curl = curl_easy_init();
if(curl) {
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

但是当我运行这段代码时,我得到

HTTP Status 415 - Cannot consume content type
Cannot consume content type
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

我用调试器检查过,即使我将内容类型设置为 xml,它也会出现

0087: Accept: */*
0094: Content-Length: 173
00a9: Content-Type: application/x-www-form-urlencoded

有人可以帮我弄清楚发生了什么吗?非常感谢!

最佳答案

当您将 headers 传递给 curl_easy_setopt 时,它仍然是一个空指针(即空列表),因此您的标题行不会成为您请求的一部分!

函数curl_slist_append,在您的情况下是两个调用

curl_slist_append(headers, "Accept: application/xml");
curl_slist_append(headers, "Content-Type: application/xml");

返回指向新列表的指针,您应该将其分配给列表变量,此处为headers。该函数基本上从尾部到前端向后构造一个链表。 Please consult the documentation of the function, especially have a look at the example code.

因此,在对 curl_slist_append 的两次调用前面添加 headers = 应该可以解决问题:

headers = curl_slist_append(headers, "Accept: application/xml");
headers = curl_slist_append(headers, "Content-Type: application/xml");

关于c++ - 内容类型 : application/x-www-form-urlencoded in curl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296555/

相关文章:

c++ - 我怎样才能让 OnLButtonDown() 事件中的进程一次又一次地发生,直到我按下按钮?

c++ - 优化与未优化构建的 KCachegrind 输出

python - mujoco_py.MjModel(<filepath>) 在哪里定义?

c++ - 在 RHEL Linux 中,使用分配有 ""(空字符串值)的 std::string 变量会给出垃圾值

c++ - curl_easy_init 失败时如何获取错误原因

c++ - 带有 header 的发布请求中出现错误 411(需要长度),但 header 具有 Content-Length。库 curl

c++ rapidjson 解析 CURLOPTS 内容的错误

curl - 如何在 cURL post 请求中发送简单对象

Windows curl 批处理文件

curl - SSL:无法从对等证书获取公用名