1. 前提
在API接口开发中,经常会碰到一个场景,就是请求第三方接口,然而请求回来的接口数据并不是我们期望的数据那样。比如我们请求回来的数据是不希望带header头信息的数据,然而第三方接口返回数据格式偏偏有header头的信息,怎么办呢?下面展示两种做法:
$no = "9830106220207";
$appcode = "6e8a1e3ee8fc4ddda7d6cc5bf999d53d";
$host = "https://kuaidi101.market.alicloudapi.com";
$path = "/getExpress";
$method = "GET";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "NO=". $no ."&TYPE=AUTO";
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
if (1 == strpos("$".$host, "https://"))
{
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
2. 方法一
$result = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); // 获取header长度
$body = substr($result, $headerSize); // 截取掉header
}
3. 方法二
$result = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
// 通过两个回车换行来分割header和body
list($header, $body) = explode("\r\n\r\n", $result, 2);
}