我正在尝试编写一个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
有人可以帮我弄清楚发生了什么吗?非常感谢!
最佳答案
当您将 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/