Php 使用CURL传递JSON数据
我正在将一个CURL post用于现有的API。API返回错误Php 使用CURL传递JSON数据,php,laravel,Php,Laravel,我正在将一个CURL post用于现有的API。API返回错误内容必须是JSON或纯文本。Ijson\u编码数据并将编码后的数据发布到API 在API中,它说内容类型应该是application/x-www-form-urlencoded' 但是,它仍然返回错误内容必须是JSON或纯文本。在以JSON格式提交数据后,下面的代码可能会出现什么问题 这是API文档中的一个示例请求正文 "item" : "Store", "content"
内容必须是JSON或纯文本。Ijson\u编码
数据
并将编码后的数据发布到API
在API中,它说内容类型应该是application/x-www-form-urlencoded'
但是,它仍然返回错误内容必须是JSON或纯文本。在以JSON格式提交数据后,下面的代码可能会出现什么问题
这是API文档中的一个示例请求正文
"item" : "Store",
"content" : {
"channel":"false",
"hop": "false",
"msg": "Order successfully placed."
}
控制器
public function postUrl()
{
$url = "https://api.com/";
$data = array("item" => "Nike Shoes","content" => array ("channel" => "false" ,"hop" => "false","msg" => "Item Sold"));
$postdata = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postdata);
}
这可能是因为布尔值被指定为字符串
public function postUrl()
{
$url = 'https://api.com/';
$data = [
'item' => 'Nike Shoes',
'content' => [
'channel' => false,
'hop' => false,
'msg' => 'Item Sold'
]
];
$postData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postData);
}
也试试这个
public function postUrl()
{
$url = 'https://api.com/';
$data = [
'item' => 'Nike Shoes',
'content' => [
'channel' => 'false',
'hop' => 'false',
'msg' => 'Item Sold'
]
];
$postData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/json']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postData);
}