自己常用的一個http請求類,和常用的區別是假如對方返回數據有utf8的bom頭會自動去掉,防止解析數據出錯
經常對接接口的同學可能碰到過一個問題:就是明明看著對方返回的數據是對的,可json_decode解碼總是出錯。那其中一個原因可能就是:對方返回的數據是utf8的並且帶著BOM頭!
此代碼特別的地方就是,假如有bom頭會自動去掉。
以下是
源代碼
class HttpSvc
{
const TIME_OUT = 3;
static $ALL_CURL = array('post','get');
public static function httpReqUrl($url,$method='get',$timeout=1)
{
if(!in_array(strtolower($method),self::$ALL_CURL))
return $url;
if(!$url)
return ;
$param = array();
$urlarr = explode("?",$url,2);
$url = $urlarr[0];
if(isset($urlarr[1]) && !empty($urlarr[1])) {
parse_str($urlarr[1],$param);
}
$res=self::HttpReqArr($url,$param,$timeout,strtolower($method));
return $res['data'];
}
public static function HttpReqArr($url,$opts=array(),$timeout=3,$mothod='post',$proxy=null)
{
$data=array();
// $logger = Logger::ins();
try{
$stime=microtime(true);
$url = trim($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
if($proxy)
curl_setopt($ch,CURLOPT_PROXY,$proxy);
if(isset($opts) && count($opts)>0)
{
$pstring='';
foreach($opts as $key => $val)
$pstring .= trim($key) . '=' . urlencode(trim($val)) . "&";
$pstring = substr($pstring,0,-1);
if(strtolower($mothod)=='post') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pstring);
curl_setopt($ch, CURLOPT_URL, $url);
}
else
{
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_URL, $url."?".$pstring);
}
}
else
{
if(strtolower($mothod)=='post')
curl_setopt($ch, CURLOPT_POST, true);
else
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_URL, $url);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$r = curl_exec($ch);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
$etime=microtime(true);
$usetime=$etime-$stime;
// $logger->debug("[response] code: $http_code, usetime: $usetime, url:$url");
$error = curl_error($ch);
if($error){
// $logger->error("code: $http_code, usetime: $usetime, callbackUrl:$url?$pstring method:$mothod opt=".var_export($opts,true).'&proxy='.$proxy);
}
}catch(Exception $e) {
// $logger->error("code: $http_code, usetime: $usetime, callbackUrl:$url?$pstring method:$mothod opt=".var_export($opts,true).' exception '.$e->getMessage()."&proxy=$proxy");
}
curl_close($ch);
$r = self::RemoveBom($r);
$data=array('code'=>$http_code,'data'=>$r);
// $logger->info("code: $http_code, usetime: $usetime, method:$mothod,callBackUrl:$url?$pstring ,putData:".$r.",proxy=$proxy");
return $data;
}
public static function RemoveBom($content)
{
if(substr($content, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
$content=substr($content, 3);
}
return $content;
}
}