php封装一个通用请求方法
浏览:1029 时间:2019-09-01 15:38:34
/**
* @param string $url 请求地址
* @param string $params 请求的参数
* @param string $method 发送请求的类型 如:GET POST
* @param string $header 头部参数
*/
function request($url,$params,$method,$header = [],$gzip = false,$httpcode = false){
if(!$url) return;
$ch = curl_init();
if($method == 'get'){
$paramsUrl = http_build_query($params);
if(strpos($url,'?')){
$url .= '&'.$paramsUrl;
}else{
$url .= '?'.$paramsUrl;
}
}else{
curl_setopt($ch,CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
}
if($header){
curl_setopt($ch, CURLOPT_HTTPHEADER , $header);
}
if($gzip) curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL , $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , 0);
$cEncode = curl_exec($ch);
if($httpcode){
$cEncode = [
'cEncode'=>$cEncode,
'httpCode'=>curl_getinfo($ch,CURLINFO_HTTP_CODE)
];
}
curl_close($ch);
return $cEncode;
}
标签:
php