【发布时间】:2017-11-22 13:19:26
【问题描述】:
我正在使用 curl 发送 JSON 格式的 JSON 字符串来发布 JSON 数据。
我使用了以下 curl 命令:
curl -H "Content-Type: application/json" -d '{ "Mode":"Auto","Type":"Single","IP":"9.9.9.9","FirmwarePath":""}' http://1.1.1.1/cgi-bin/update_firmware.cgi
上述命令的输出:
<h1>{ "Mode":"Auto","Type":"Single","IP":"9.9.9.9","FirmwarePath":""} </h1><h1>Check Mode</h1><h1>Auto</h1><h1>Single</h1><h1 /><h1>Here Mode</h1><h1>{ "Mode":"Auto","Type":"Single","IP":"9.9.9.9","FirmwarePath":""}</h1><h1>Check Input</h1><h1>Inside Firmware updates</h1><h1>In CheckFirmware</h1><h1>curl -s --digest --basic -u root:UOIYTm7Aw52Z "http://9.9.9.9/axis-cgi/operator/param.cgi?action=list&group=Properties.Firmware.Version" | cut -d'=' -f2</h1><h1>cam Firm:5.50.4.2
</h1><h1>DB Firm: </h1>Status: 200
Content-Type: application/json; charset=ISO-8859-1
{"ReqStatus":{"Status":"Firmware is upto date or Firmaware update mode is off.","IP":null}}
所以,它工作正常并给了我预期的输出。
现在我希望将此输出存储在文本文件中。因此,我编写了 C 程序来实现这一点:
#include <stdio.h>
#include <curl/curl.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp = fopen("request.txt","w");
CURLcode res;
curl = curl_easy_init();
char* jsonObj = "{\"Mode\":\"Auto\",\"type\":\"Single\",\"IP\":\"9.9.9.9\",\"FirmwarePath\":\"""\"}";
puts(jsonObj);
struct curl_slist *headers = NULL;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append(headers, "Content-Type: application/json");
curl_slist_append(headers, "charsets: utf-8");
curl_easy_setopt(curl, CURLOPT_URL, "http://1.1.1.1/cgi-bin/update_firmware.cgi");
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,write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA,fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
但是当我打开 request.txt 文件时执行这个 C 程序后,我看到了意外的输出。
request.txt 文件内容:
<h1>Software error:</h1>
格式错误的 JSON 字符串,既不是数组、对象、数字、字符串也不是原子,位于 /var/www/cgi-bin/update_firmware.cgi 第 496 行的字符偏移量 0(“(字符串结尾)”之前)
<p>
For help, please send mail to the webmaster (<a href="mailto:root@localhost">root@localhost</a>), giving this error message
and the time and date of the error.
</p>
我要发送的 JSON 数据是:
{
"Mode":"Auto",
"Type":"Single",
"IP":"9.9.9.9",
"FirmwarePath":""
}
我在这里做错了什么?
【问题讨论】: