2014-05-03 118 views
0

我在使用file_get_contents调用休息服务时遇到了一个问题 它在响应成功时正常工作,但在失败或错误响应时给出空白结果。而当我使用休息客户端进行检查时,无论是成功还是失败,都会给予我正确的答复。休息服务问题

任何人都可以请帮忙吗?下面是我写的源代码。

<?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

您是否尝试在上下文选项中添加“'ignore_errors'=> true”? –

+0

我从来没有见过'file_get_contents'与REST Web服务一起使用。它不应该像那样使用。 REST依靠HTTP通信。这意味着除了设置请求之外,您还必须解析响应。 'file_get_contents'不允许。 CURL的确如此。 http://stackoverflow.com/questions/9659079/file-get-contents-vs-curl-for-invoking-apis-with-php – AlexanderMP

+0

@AlexanderMP“它不应该像这样使用”听起来很像一个观点; php流对于REST服务消耗很好;不确定你的意思是“cURL允许响应解析”。 –

回答

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