我有以下数据通过我的API发布到服务器。
Request Body:
{
"nutrients": {
"protein": "beans",
"fats": "oil",
"carbohdrate": "starch"
}
}
每次运行脚本时,都会出现以下错误
{"errors":[{"status":"400","code":"031","title":"payload not parseable","detail":"Invalid formatting of the request payload."},{"status":"400","code":"026","title":"payload missing","detail":"No payload describing the resource object included in the request."}]}
这似乎是因为我没有添加变量"营养素"在要发布的数据数组中。
有人能帮助我吗?以下是我到目前为止的努力。感谢
<?php
$url = "https://myapi_site.com/server/";
$data = array(
'protein' => 'beans',
'fats' => 'oil',
'carbohdrate' => 'starch'
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
?>
答案 0 :(得分:0)
您发布的PHP数组尚未转换为JSON ...您想发布JSON本身。以下是发布JSON字符串的方法。
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
您可以使用json_encode
将PHP数组编码为JSON:
定义您的$data
变量,如下所示:
$data = array(
'nutrients' => array(
'protein' => 'beans',
'fats' => 'oil',
'carbohdrate' => 'starch',
),
);
您可以回显$data
变量以查看它包含正确的JSON数据:
echo $data;