我已经向 REST API 发出了一个 oauth 签名请求,并将响应 header 放在一个数组中,如下所示:
[0] => HTTP/1.1 200 OK
[1] => Cache-Control: private
[2] => Transfer-Encoding: chunked
[3] => Content-Type: text/html; charset=utf-8
[4] => Content-Location: https://***
[5] => Server: Microsoft-IIS/7.0
[6] => Set-Cookie: ASP.NET_SessionId=***; path=/; HttpOnly
[7] => X-AspNetMvc-Version: 2.0
[8] => oauth_token: ***
[9] => oauth_token_secret: ***
[10] => X-AspNet-Version: 4.0.30319
[11] => X-Powered-By: ASP.NET
[12] => Date: Sat, 15 Sep 2012 02:01:15 GMT
我想知道如何解析 header 以便轻松检索 HTTP 状态代码、内容位置、oauth_token 和 oauth_token_secret 等项目?
您需要遍历数组并检查 stripos()
以找到您要查找的 header 。在大多数情况下,您然后在 :
上执行 explode()
(限制为 2 个结果部分),但 HTTP 响应代码将要求您在空格处展开。
// Get any header except the HTTP response...
function getResponseHeader($header, $response) {
foreach ($response as $key => $r) {
// Match the header name up to ':', compare lower case
if (stripos($r, $header . ':') === 0) {
list($headername, $headervalue) = explode(":", $r, 2);
return trim($headervalue);
}
}
}
// example:
echo getResponseHeader("Content-Type");
// text/html; charset=utf-8
// Get the HTTP response code
foreach ($response as $key => $r) {
if (stripos($r, 'HTTP/') === 0) {
list(,$code, $status) = explode(' ', $r, 3);
echo "Code: $code, Status: $status";
break;
}
}