繁体   English   中英

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

[英]How send POST request with JSON in php?

我尝试将请求从帖子类型发送到服务器,但没有成功,它返回状态为 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);

?> 

它让我回复:

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

我看到您准备$payload要发送的变量$payload ,但在curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata)处发送了$postdata

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM