首页 > 解决方案 > 如何在 php 中发送 POST 请求?

问题描述

我尝试从帖子类型向服务器发送请求,但没有成功,它返回状态为 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"] => string (51) "Bad Request: Syntax error, distorted JSON" ["status"] => int (400)} 但它让我返回 false

标签: phpcurlposthttps

解决方案


You set the Content-Type request header to application/json

Then you use CURLOPT_POSTFIELDS which is not for JSON, but a query string.

Change your headers to this:

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

And skip the http_build_query()

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

推荐阅读