php获取请求body,php使用curl发送post请求并获取响应header和body

最近项目对接的时候需要发送http请求,所以会用到curl,调试了好久终于调试好了,现在发布下写法。注意需要设置发送头,是json格式的还是其他的application

private function sendMsg($data)

{

import('Encode.Encode');

$encode = new \Encode\Aes();

$url['http'] = $data['vediourl'];

$info = json_encode($url['http']);

$info = $encode->encrypt($info);

$up['transid'] = intval($data['id']);

$up['cpid'] ='0001000001001234';

$up['filetype']=2;

$up['filesize']=intval($data['size']);

$up['filemd5']=$data['hash'];

$up['fileinfo']=$info;

$up['userid']=$data['userid'];

$up['timestamp']=date('Ymdhis',time());

$up['sign']= md5($data['id'].$up['cpid'].$up['filetype'].$data['size'].$data['hash'].$data['vediourl'].$data['userid'].$up['timestamp']);

$post = json_encode($up);

$ch = curl_init ();

$headers= array('Accept: application/json','Content-Type: application/json');

curl_setopt ( $ch, CURLOPT_URL, $this->posturl );

curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt ( $ch, CURLOPT_HEADER, TRUE);    //表示需要response header

curl_setopt ( $ch, CURLOPT_NOBODY, FALSE);  //表示需要response body

curl_setopt ( $ch, CURLOPT_POST, 1 );//采用post

curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post );

curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, FALSE);

curl_setopt ( $ch, CURLOPT_AUTOREFERER, TRUE);

curl_setopt ( $ch, CURLOPT_TIMEOUT, 120);

$response=curl_exec ( $ch );

\think\Log::record('测试发送CDN'.$post);

\think\Log::record('测试发送CDN'.$response);

if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {

$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

$header = substr($response, 0, $headerSize);

$body = substr($response, $headerSize);

$res = json_decode($body); // 解析回来的数组

if($res['code'] == '0')

{

}

else

{

echo $res['message'];

}

}

curl_close ( $ch );

}

curl参数很多附上参数说明吧:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值