繁体   English   中英

如何获取php file_get_contents()错误响应内容

[英]How to get php file_get_contents() error response content

我尝试用PHP使用.net WebAPI。 没有错误时一切正常。 但是当WebApi中出现一些错误时(假设POST数据验证失败)我很容易得到响应头,但我无法找到如何获取响应内容,以便我可以阅读导致错误的原因。

有人知道如何获得或不可能吗?

在WebAPI的testController上有一个test()动作,它需要id和text作为请求的内容,否则它将返回HTTP / 1.1 400 Bad Request,内容告诉原因。

我用fiddler来测试WebAPI:

POST http://localhost:56018/api/test/test
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:56018
Content-Length: 32
Content: {"id": 5,"text" : '',}

回应是:

HTTP/1.1 400 Bad Request
...
Content-Length: 304

{"args.Text":{"_errors":[{"<Exception>k__BackingField":null,"<ErrorMessage>k__BackingField":"The Text field is required."}],"<Value>k__BackingField":null},"Text":{"_errors":[{"<Exception>k__BackingField":null,"<ErrorMessage>k__BackingField":"The Text field is required."}],"<Value>k__BackingField":null}}

所以它在内容中告诉“文本字段是必需的”。

与php完成相同:

$opts = array('http' =>
    [
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => http_build_query(['id' => 1, 'text' => '']),
        'ignore_errors' => true,
    ]
);
$context  = stream_context_create($opts);
$response = file_get_contents('http://localhost:56018/api/test/test', false, $context);
if($response === false)
{
    echo json_encode($http_response_header);
    die;
}
else
{
    ...
}

所以我从$ http_response_header获取响应头数据,但是我找不到任何方法来获取我在Fiddler看到的响应内容。

有人知道如何获得或不可能吗?

最后一个提示cURL不是正确答案; P

编辑:在这种情况下($ response === false),也许值得一提的是$ http_response_header中的内容:

array (
  0 => 'HTTP/1.1 400 Bad Request',
  1 => 'Cache-Control: no-cache',
  2 => 'Pragma: no-cache',
  3 => 'Content-Type: application/json; charset=utf-8',
  4 => 'Expires: -1',
  5 => 'Server: Microsoft-IIS/10.0',
  6 => 'X-AspNet-Version: 4.0.30319',
  7 => 'X-SourceFiles: =?UTF-8?B?QzpcZG90TmV0NDBcR2FsbGUyV2ViQXBpXEdhbGxlMldlYkFwaVxhcGlcZ2FsbGUyXFRlc3Q=?=',
  8 => 'X-Powered-By: ASP.NET',
  9 => 'Date: Wed, 01 Jun 2016 06:33:11 GMT',
  10 => 'Connection: close',
  11 => 'Content-Length: 304',
)

您可以尝试使用curl而不是file_get_contents因为curl可以更好地支持错误处理:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:56018/api/test/test"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch);   

$output = json_decode($output);

if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
  var_dump($output);
}

curl_close($ch);

所以最后发布的所有内容都应该如此。 在来到这里之前我应该​​做一个孤立的测试用例。 (但是在调试之后,似乎你已经尝试了所有选项:P)

所以我认为'ignore_errors'=> true,行被某种方式覆盖或忽略,但是将它隔离成它所假设的其他代码以及$ response的值,如果错误消息的内容。

因此,在这种情况下,您需要以if($ response === false)之外的其他方式进行错误检查。 非常简单的方法可能是if($ http_response_header [0]!='HTTP / 1.1 200 OK'){处理错误! }

感谢每一个输入!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM