如何在php中使用JSON发送POST请求?

时间:2020-09-23 19:18:31

标签: php post https

我尝试将请求从帖子类型发送到服务器,但未成功,它返回状态为400的BadRequest,

我的代码:

<?php

$products = array('1'=>array('amount'=>'1','product_id'=>'11250'));
$data = array('id' => '67', 'shipping' => '61', 'payment'=> '2','products'=> $products);
$cert = base64_encode('myapp@myapp.co.il:1234abcd');
$url = "https://myapp.co.il/api/aaa";


$ch = curl_init($url);
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "authorization: Basic ".$cert,
    "Content-Type: application/json",
    "cache-control: no-cache"
    ));
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);

?> 

它使我返回:

array(2){[“ message”] =>字符串(51)“错误的请求:语法错误,JSON失真” [“ status”] => int(400)}

1 个答案:

答案 0 :(得分:1)

我看到您准备好发送变量$payload,但发送$postdata的位置却是curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata)

相关问题