在有的时候,我们需要通过获取接口相应的请求头信息,可以在curl_exec函数执行前,添加代码
curl_setopt($ch,CURLINFO_HEADER_OUT,true);
然后在curl_exec函数执行后,通过 curl_getinfo($ch,CURLINFO_HEADER_OUT) 来获取curl执行请求的请求数据
直接上代码:
public static function httpRequest($url, $method = 'GET', $params = null, $headers = array(), $pem = array(), $debug = false, $timeout = 60) { $method = strtoupper($method); $ci = curl_init(); curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_setopt($ci, CURLOPT_USERAGENT, 'Google/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'); // curl_setopt($ci, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_POST, TRUE); if(!empty($params)) { $tmpdatastr = is_array($params) ? http_build_query($params) : $params; curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr); } curl_setopt($ci, CURLOPT_URL, $url); curl_setopt($ci, CURLOPT_MAXREDIRS, 2); curl_setopt($ci, CURLOPT_HTTPHEADER, $headers); curl_setopt($ci, CURLINFO_HEADER_OUT, true); curl_setopt($ci , CURLOPT_HEADER, true ); $response = curl_exec($ci); $requestinfo = curl_getinfo($ci); $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $headerSize = curl_getinfo($ci , CURLINFO_HEADER_SIZE); $headerStr = substr( $response , 0 , $headerSize ); $bodyStr = substr( $response , $headerSize ); $responseHeader = self::headerHandler($headerStr); yii::info('响应header信息'.json_encode($responseHeader), 'app'); yii::info('响应body信息'.$bodyStr, 'app'); if($debug) { echo "=====post data======\r\n"; var_dump($params); echo "=====info===== \r\n"; print_r($requestinfo); echo "=====response=====\r\n"; print_r($response); } curl_close($ci); return $bodyStr; } public static function headerHandler($str) { $headers = array(); $headersTmpArray = explode("\r\n", $str); for($i = 0; $i < count($headersTmpArray); ++$i) { if(strlen($headersTmpArray[$i]) > 0) { if(strpos($headersTmpArray[$i], ':')) { $headerName = substr($headersTmpArray[$i], 0, strpos($headersTmpArray[$i], ':')); $headerValue = substr($headersTmpArray[$i], strpos($headersTmpArray[$i], ':') + 1); $headers[$headerName] = $headerValue; } } } return $headers; }
看一下结果:
这个是响应头的信息:
可以看到里面可以设置一些请求id之类的东西。
来源地址:https://blog.csdn.net/lchmyhua88/article/details/129475374