休息服务问题

时间:2014-05-03 08:52:27

标签: php rest

当我使用file_get_contents调用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;
?>

1 个答案:

答案 0 :(得分:0)

如果你想坚持使用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