我有这个代码:
#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_URL, "localhost/rest-v1/devices/did1/tasks");
curl_easy_setopt(curl,CURLOPT_PORT,22080);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"hello\" : \"darkness\"}");
res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
return 0;
}
当我运行它时,我在控制台上打印了这个:
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 22080 (#0)
> POST /rest-v1/devices/did1/tasks HTTP/1.1
Host: localhost:22080
Accept: */*
Content-Length: 16
Content-Type: application/x-www-form-urlencoded
* upload completely sent off: 16 out of 16 bytes
< HTTP/1.1 415 Unsupported Media Type
< Server: Restlet-Framework/2.3.9
< Date: Fri, 23 Jun 2017 06:44:09 GMT
< Content-type: application/json; charset=UTF-8
< Content-language: *
< Content-length: 35
< Accept-ranges: bytes
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
因此它返回 415 Unsupported Media Type 错误代码。
我在StackOverflow上查到可能是Context-type中的charset=UTF-8导致的。 所以我的问题是,如何编辑此字段以满足我的需要(删除 charset=UTF-8)。 link
如何更改该内容类型。由于我是 HTTP 协议(protocol)的新手,请详细说明。
最佳答案
根据 URL /rest-v1/devices/did1/tasks
,您正在使用 IBM Business Process Manager REST Interface。文档指出:
Media Types
The data included in requests or responses will be of one of the following media types:
application/json: JSON (JavaScript Object Notation) - This is the default response content type. For the detailed format of each returned object, see the JSON schema specifications for each operation.
application/xml: XML (eXtensible Markup Language) - The format of XML-based data is specfied by the XML schemas supplied with the product in the /properties/schemas/bpmrest/v1 directory. Excerpts of these schemas are also provided in the documentation for each operation.
application/x-javascript: JSONP (JSON with Padding) - This format can be used as an alternative to JSON. In this case, each returned JSON response is wrapped in a JavaScript callback function invocation. To use this feature, you must also specify the callback URI query parameter.
因此您必须为您的请求选择这些内容类型之一(不是上下文类型!),而不是 application/x-www-form-urlencoded
。在您的示例代码片段中,您使用 JSON,因此此处的适当数据类型是 application/json
。您可以按如下方式设置:
struct curl_slist *hs=NULL;
hs = curl_slist_append(hs, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs);
这应该可以消除您观察到的 HTTP 错误 415。
关于使用 libcurl 更改内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44715069/