【问题标题】:Gettting body with PHP when response code is 201响应代码为 201 时使用 PHP 获取正文
【发布时间】:2018-04-21 11:28:11
【问题描述】:

我需要与 REST 网络服务器交互。当我发出请求时,它会(正确地)响应 HTTP 响应代码 201(已创建)以及正文中的相关信息(JSON 对象)。

我可以使用 cURL 验证它。

我正在尝试通过 PHP 的 file_get_contents 函数获取正文,指定正确的上下文对象,代码如下:

$context = stream_context_create(array(
     'http' => array(
       'method' => 'POST',
       'header' => $header,
       'timeout' => 10.0,
       'content' => $body,
            'ignore_errors' => true
      )
    )
);

$answer = file_get_contents($url, false, $context);

但是该函数总是返回一个假值,我无法得到返回的主体。

我能做什么? (我宁愿不从 PHP 调用 cURL)

【问题讨论】:

  • php 本身有 curl 方法。无需从 shell 调用 curl 。 stackoverflow.com/questions/17134546/….
  • file_get_contents 应该返回你的身体。也许您的请求由于某种原因而失败。
  • 更好的是,Guzzle 是一个非常好的 curl 包装器。
  • 您可以建议他使用 curl 或 Guzzle,但它没有回答为什么 file_get_contents 不能按预期工作(它应该工作!)。
  • 也许我发现 http 上下文选项提供了子句 ignore_errors

标签: php http http-response-codes


【解决方案1】:

好的,我找到了。 原因是旧的php版本, 那没有处理'ignore_errors'参数。 切换到更新版本的 php,现在它可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2018-06-13
    相关资源
    最近更新 更多