在很多时候,我们都需要请求第三方的服务器来获取一些数据,比如token,比如百度的主动推送,那么我们的php如何实现向第三方服务器发请求呢?我们可以通过curl来实现
首先定义请求的url,然后创建httpHeader的头,定义通过post方式发送请求的参数:初始化curl:
$url="URL地址"; //然后创建httpHeader的头: $httpHeader=createHttpHeader(); //定义通过post方式发送请求的参数: $curlPost="userId=".$userId."&name=".$nickName."&portraitUri=".$headImg; //初始化curl: $ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeader); curl_setopt($ch,CURLOPT_HEADER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); curl_setopt($ch,CURLOPT_TIMEOUT,30); curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE,false); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
接收返回的数据:$data=curl_exec($ch);关闭curl:curl_close($ch);这样就通过curl完成了一次post请求,并获取到了返回的数据。
$url="请求的URL地址"; $httpHeader=createHttpHeader(); $curlPost="userId=".$userId."&name=".$nickName."&portraitUri=".$headImg; $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeader); curl_setopt($ch,CURLOPT_HEADER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); curl_setopt($ch,CURLOPT_TIMEOUT,30); curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE,false); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $data=curl_exec($ch); curl_close($ch);