1.通过curl发送json格式的数据,譬如代码:
function http_post_json($url, $jsonStr)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($jsonStr)
)
);
$response = curl_exec($ch);
//$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $response;
}
$api_url = 'http://fecshop.appapi.fancyecommerce.com/44.php';
$post_data = [
'username' => 'terry',
'password' => 'terry4321'
];
然后在接收端,使用$_POST接收,发现打印是空的
原因是,PHP默认只识别application/x-www.form-urlencoded标准的数据类型,因此接收不到,只能通过
//第一种方法
$post = $GLOBALS['HTTP_RAW_POST_DATA'];
//第二种方法
$post = file_get_contents("php://input");
来接收
2.如果我们在Yii2框架内,想通过
$username = Yii::$app->request->post('username');
$password = Yii::$app->request->post('password');
这种方式获取第一部分使用curl json方式传递的post参数,我们发现是不行的,我们需要设置yii2 request component
'request' => [
'class' => 'yii\web\Request',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
然后