当我使用file_get_contents调用rest服务时,我面临一个问题响应成功时工作正常,响应失败或错误时给出空白结果。而当我使用rest客户端检查它时,它会给我正确的响应,无论是成功还是失败。
有人能帮忙吗?下面是我编写的源代码。
<?php
$postdata = array(
'email' => $email,
'password' => $password
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => $headers = array(
'Accept: application/json',
'Content-Type: application/json'
)
//'content' => $postdata
)
);
$context = stream_context_create($opts);
//echo "<pre>"; print_r($context); exit;
$url = WS_URL . "issavvy-api/account/login?" . http_build_query($postdata);
$result = file_get_contents($url, false, $context);
echo "<pre>";
print_r(json_decode($result));
exit;
?>
如果你想继续使用file_get_contents使用$http_response_header并解析它
你可以使用
function httpStatusCode($headers){
$match = null;
$pattern = "!(?P<version>HTTP/'d+'.'d+) (?P<code>'d+) (?P<status>.*)!";
foreach($headers as $header){
if(preg_match($pattern, $header, $match)){
return $match['code'];
}
}
return null;
}
检查请求是否成功运行
$success = (200 == httpStatusCode($http_response_header));
https://eval.in/145906