我正在使用 C 中的 libcurl 定义一个带有 JSON 请求正文的 PUT 请求。
这就是我的做法:
sprintf(jsonObj, "\"name\" : \"%s\", \"age\" : \"%s\"", name, age);
struct curl_slist *headers = NULL;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append(headers, "Content-Type: application/json");
curl_slist_append(headers, "charset: utf-8");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");
res = curl_easy_perform(curl);
请求正文是这样到达的:
{ '"name" : "Pedro", "age" : "22"' }
在{ '
开始和' }
结束时。
- - 更多信息 - - -
如果我声明此代码
char* jsonObj = "{ \"name\" : \"Pedro\" , \"age\" : \"22\" }";
struct curl_slist *headers = NULL;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append(headers, "Content-Type: application/json");
curl_slist_append(headers, "charset: utf-8");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");
res = curl_easy_perform(curl);
服务器将其作为请求正文接收:
{ '{ "name" : "Pedro" , "age" : "22" }': '' }
我的问题是:
libCurl 是否自动预格式化/编码 Json 请求?
顺便说一句,libCurl 是否有某种方式对 JSON 对象进行编码?
非常感谢!