php 用curl 进行数据post给接口,如何将数据存放至body中传递
有个项目,将数据推送至接口文件,代码入下:
$headers[] = "Accept:application/json";
$headers[] = "Authorization: Bearer ". $accessToken;
$ch = curl_init() or die (curl_error());//打开
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arr));
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
$response = curl_exec($ch);
curl_close($ch);//关闭
其中$arr是需要提交的数组数据,比如:
$arr['name'] = '123';
这样访问后,接口出无法从body中获取到数据。然后修改代码:
$headers[] = "Accept:application/json";
$headers[] = "Authorization: Bearer ". $accessToken;
$headers[] = "Content-Type:application/json";
$ch = curl_init() or die (curl_error());//打开
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arr));
if( !empty($header) ){
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
}
$response = curl_exec($ch);
curl_close($ch);//关闭
头部添加content-type为json,提交数据这边把数据改成json提交。对方接口成功从body中获取到数据