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

hykeda3年前PHP1769

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

$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

相关文章

简单的高精度计算函数

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

抓取页面出现乱码

在抓取页面的时候出现类似�������这样乱码解决方法如下 1、转换编码 str=mbconvertencoding(str=mbconvertencoding(...

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

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

php导出EXCEL出现错误解决方法

由于数据量不多的增多,最近出现了导出excel的时候报错:Allowed memory size of 134217728 bytes exhausted (tried to allocate 114...

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

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

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

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

发表评论    

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