php - 如何在 PHP 中解析响应头?

标签 php api rest http-headers

<分区>

我已经向 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;
  }
}

关于php - 如何在 PHP 中解析响应头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433958/

相关文章:

php - 如何获取指定字符之前的1个字符

php - 使用 PHP 更新 MySQL 数据库时出错

php - 来自数据库的同位素过滤库

mysql - 最近从 sqlite 切换到 mysql。需要在c中转换一些代码

javascript - 使用 Cypress 在命令行中传递自定义 API key

php - ajax问题(页面刷新)

python - 使用 Python API 下载数据时如何消除(或从控制台抑制)Interactive Brokers 错误

rest - API Blueprint 与 Swagger 的独特目的是什么?

java - 从 queryForList() 方法返回数据 - 类型不兼容错误

rest - 如何在 REST 客户端上测试我发布的 LEX 机器人