如何在php中发送POST请求?

时间:2020-09-23 17:37:31

标签: php curl post https

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

我的代码:


$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');
$header = array(
   "authorization: Basic ".$cert,
   "Content-Type: application/json",
   "cache-control: no-cache"
   );
$url = "https://myapp.co.il/api/aaa";

$curl = curl_init($url);
//curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response,true);

var_dump($response);

?> 

它使我返回:

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

1 个答案:

答案 0 :(得分:0)

您将Content-Type请求标头设置为application/json

然后,您使用CURLOPT_POSTFIELDS(不是用于JSON,而是查询字符串)。

将标题更改为此:

$header = [
   'authorization: Basic '.$cert,
   'Content-Type: multipart/form-data',
   'cache-control: no-cache'
];

并跳过http_build_query()

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);