pzy*_*iak 2 c post http libcurl http-headers
我有这个代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我在控制台上得到这个打印:
* 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
Run Code Online (Sandbox Code Playgroud)
所以它返回 415 Unsupported Media Type 错误代码。
我在 StackOverflow 上发现它可能是由 Context-type 中的 charset=UTF-8 引起的。所以我的问题是,如何编辑此字段以满足我的需要(删除 charset=UTF-8)。 关联
如何更改该内容类型。由于我是 HTTP 协议的新手,请详细说明。
根据 URL,/rest-v1/devices/did1/tasks您正在使用IBM Business Process Manager REST Interface。该文件指出:
媒体类型
请求或响应中包含的数据将是以下媒体类型之一:
application/json : JSON (JavaScript Object Notation) - 这是默认的响应内容类型。每个返回对象的详细格式,请参见每个操作的 JSON 模式规范。
application/xml : XML (eXtensible Markup Language) - 基于 XML 的数据格式由 /properties/schemas/bpmrest/v1 目录中随产品提供的 XML 模式指定。每个操作的文档中还提供了这些模式的摘录。
application/x-javascript : JSONP (JSON with Padding) - 这种格式可以作为 JSON 的替代。在这种情况下,每个返回的 JSON 响应都包含在 JavaScript 回调函数调用中。要使用此功能,您还必须指定回调 URI 查询参数。
因此,您必须为您的请求选择这些 Content-Type 之一(不是 Context-Type!)而不是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);
Run Code Online (Sandbox Code Playgroud)
这应该可以消除您观察到的 HTTP 错误 415。
| 归档时间: |
|
| 查看次数: |
7266 次 |
| 最近记录: |