2014-05-03 121 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