【问题标题】:Content-Type: application/x-www-form-urlencoded in curl内容类型:curl 中的 application/x-www-form-urlencoded
【发布时间】:2014-08-13 21:34:51
【问题描述】:

我正在尝试编写一个 c++ 程序,它使用 curl 库在 Red 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

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

【问题讨论】:

  • @leemes 谢谢你,这真的很有帮助。

标签: c++ curl libcurl


【解决方案1】:

当您将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");

【讨论】:

  • 一个公平的后续问题是:为什么这个有趣的 API?事实是,它从来都不是一个好的 API,但它是偶然出现的,我们一直坚持使用它,以免破坏任何旧应用程序..
  • @DanielStenberg 完全同意。事实上,向后兼容性通常是丑陋的库 API 的主要原因;)(最好的例子是 PHP!)我什至不知道 curl 如何处理链表,但我发现只传递一个 null 是没有意义的指向 C 函数的指针(不能修改它,因为 C 没有引用)。然后我只是简单地阅读了文档并通过查看示例在 2 秒内发现了错误。 ;)
猜你喜欢
  • 2021-02-03
  • 2015-04-02
  • 1970-01-01
  • 2019-09-12
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
相关资源
最近更新 更多