你好,我正在尝试使用PHP向API发送一个post请求。
我有以下代码。API希望产品是像这样的字典列表
[{"id":1, "name": "nyan"}, {"id": 2, "name": "cat"}]
我有下面的代码,它似乎正确地发送了它,但API不接受它,我假设它与PHP数组的编码方式有关,但不能真正弄清楚,任何帮助都是值得赞赏的。
<?php
$data = array(
key => "API_KEY",
private_key => "PRIVATE_API_KEY",
products => array(array(id => 73,
name => "A nice t-shirt",
description => "A nice t-shirt with a picture of a cat",
price => 9.95,
brand => "Cat t-shirts",
category => 11,
rating => 5))
);
$data_string = json_encode($data);
$ch = curl_init('http://api.clerk.io/v2/product/add');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: application/json');
$result = curl_exec($ch);
echo $result;
您不需要将其转换为JSON字符串,
所以删除以下行,
$data_string = json_encode($data);
并更新以下行,
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
http_build_query((从Array生成URL编码的查询字符串。
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
在标题中添加内容长度
$data = array(
key => "API_KEY",
private_key => "PRIVATE_API_KEY",
products => array(
array(id => 73,
name => "A nice t-shirt",
description => "A nice t-shirt with a picture of a cat",
price => 9.95,
brand => "Cat t-shirts",
category => 11,
rating => 5
)
)
);
$data_string = json_encode($data);
echo '<br>'.$data_string;
您将从"products"键获得产品词典。所以你只需要把"产品"的关键数据传递给API。