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

hykeda10个月前PHP324

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

$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

相关文章

discuzX3.2 用户注册接口代码

新建一个php文件在根目录,例:test.php test.php 具体内容: error_reporting(0); require_once './source/class/clas...

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

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

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

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

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

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

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

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

抓取页面出现乱码

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

发表评论    

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