c - 在 C 中发布 JSON 对象时,位置 0 处出现意外的令牌 004
问题描述
我在尝试发送我在 C 中创建的 JSON 对象时遇到问题。服务器能够很好地发送和接收数据。说到C,我是个业余爱好者。
static int main_curl(neardal_record* pRecord)
{
CURL *curl;
CURLcode res;
char * record = pRecord->representation;
json_object *jobj = json_object_new_object();
json_object *jstring = json_object_new_string(record);
json_object_object_add(jobj,"id", jstring);
curl = curl_easy_init();
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charset: utf-8");
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.43.20:5000/api/swipes");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jobj);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");
printf ("The json object created:%s ",json_object_to_json_string(jobj));
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
当打印出 JSON 对象时,我得到了这个 ->
The json object created:{ "id": "hello, world" }
服务器响应如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>SyntaxError: Unexpected token in JSON at position 0<br> at JSON.parse
(<anonymous>)<br> at createStrictSyntaxError
(/Users/backend/node_modules/body-parser/lib/types/json.js:158:10)<br>
at parse (/Users/backend/node_modules/body-
parser/lib/types/json.js:83:15)<br> at
/Users/backend/node_modules/body-parser/lib/read.js:121:18<br>
at invokeCallback (/Users/backend/node_modules/raw-
body/index.js:224:16)<br> at done
(/Users/backend/node_modules/raw-body/index.js:213:7)<br>
at IncomingMessage.onEnd (/Users/backend/node_modules/raw-
body/index.js:273:7)<br> at IncomingMessage.emit (events.js:333:22)<br>
at endReadableNT (_stream_readable.js:1201:12)<br> at
processTicksAndRejections (internal/process/task_queues.js:84:21)</pre>
</body>
</html>
当使用 Wireshark 拦截请求时,Post 看起来像这个 POST 请求 并且响应错误是这个 BAD REQUEST 400
我几乎可以肯定,错误是我构建 JSON 对象的方式,但如前所述,我在 C 语言中很新。如果我硬编码文本而不是对象,则请求成功。任何帮助将非常感激。谢谢!
解决方案
毕竟通过将其更改为此
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jobj);
来
设法弄清楚curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_object_to_json_string(jobj));
如果我错了,请纠正我,但我假设我不能只发送一个 JSON 对象而不先将其转换为字符串。
任何进一步的建议将不胜感激!
推荐阅读
- javascript - 在 for 循环中将值传递给函数不起作用
- angular - 如何在 API Requests Angular2 中出现 window.alert 错误?
- sql - Oracle SQL 获取第三张表的参考
- c++ - 在二叉搜索树中找到具有最小值的节点(打印该节点)
- cmake - CMake 是否可以始终强制编译/构建特定文件?
- python - Python,通过列的整数复制数据框中的行并相应地减少它
- sockets - 如何解决 ionic 3 中的 SocketTimeoutException
- javascript - 如果输入字段数据不正确,请阻止操作。(js)
- python - 如何处理NAT python socket
- flutter - 获取android目录中的文件列表并在flutter中添加或删除文件时更新它