php 用curl 进行数据post给接口,如何将数据存放至body中传递

hykeda2年前PHP1388

有个项目,将数据推送至接口文件,代码入下:

$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中获取到数据

标签: CURLbodyphp

相关文章

file_get_contents("php://input")的使用方法

$data = file_get_contents("php://input"); php://input 是个可以访问请求的原始数据的只读流。 POST 请求的情况下,最好使用 php:/...

composer使用phpstudy的php环境,如果改变php版本如何处理

        首先安装composer后,先在系统的环境变量中添加php路径,比如之前的路径:C:\zhangsan\...

简单的高精度计算函数

/** PHP高精度计算 * @param string $type * @param $n * ...

查找附近geohash算法及实现 (PHP版本)

随着移动终端的普及,很多应用都基于LBS功能,附近的某某(餐馆、银行、妹纸等等)。 基础数据中,一般保存了目标位置的经纬度;利用用户提供的经纬度,进行对比,从而获得是否在附近。 目标:...

关于PHP处理BOM头的问题

关于php出现无法解析数据,直接var_dump出来为string(3)"",必须警觉,极大可能就是存在bom头的问题,比如接收json数据 $rt = json_decode($r...

phpstudy提示错误:cURL error 60 配置SSL CA证书

phpstudy配置SSL CA证书本地Windows环境, phpstudy 集成 php7 后,出现错误提示:cURL error 60: SSL certificate pr...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。