最近项目对接的时候需要发送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参数很多附上参数说明吧: