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

hykeda10个月前PHP332

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

$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导出EXCEL出现错误解决方法

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

file_get_contents和curl出现400 Bad Request问题

我在使用这两个函数抓取数据的时候出现了400错误,一开始以为是http和https的问题,以为https证书问题,忽略证书后还是报400,但是输入百度的网址都正常。 其实是url参数...

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

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

百度经纬度和火星坐标转换

<?php     //GCJ-02...

php json_encode输出空白问题

php json_encode输出空白问题

例如这样的一段转json出现空白: echo json_encode(array('error' => '0', 'message' => '没有错误')); var_dump(js...

关于PHP获取IP地址的几种方法

获取客户端的ip地址有3中方式: 1.REMOTE_ADDR:浏览当前页面的用户计算机的ip地址 2.HTTP_X_FORWARDED_FOR: 记录代理信息,会把每一层代理都记录 3.HTTP_C...

发表评论    

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