php - 如何在 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
解决方案
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);
推荐阅读
- angular - 如何将数据组合到不同类型的对象数组并对其进行迭代以创建表行
- python - 想要以编程方式为“媒体文件”添加 git 以从 views.py 跟踪它们的历史记录
- python - TypeError:“str”对象不能通过 Python 使用 Selenium 调用
- php - 电子邮件动态内容与 foreach 内的第一个循环值重复
- rust - 关于 Rust 中的所有权/生命周期的困惑
- json - 如何在 bash 中使用 Mandrill API 正确发送 html 以使用 cURL?
- pdfbox - 在 pdf 中删除旧修订并仅保留最后一个
- c# - 如何使用不记名令牌发布 JSON
- flutter - 在颤振中更改 UnderlineInputBorder 属性
- kiwi-tcms - 如何在 kiwiTCMS 中更改域名?