2014-09-04 25 views
0

我需要從PHP發送POST請求到遠程HTTPS地址,該地址返回JSON。file_get_contents()可以在4xx上返回HTML嗎?

我用下面的代碼:

//$url = ... 
    $data = array('username' => $username, 'password' => $passwort); 

    $options = array(
     'http' => array(
      'header' => "Content-type: application/x-www-form-urlencoded\r\n", 
      'method' => 'POST', 
      'content' => http_build_query($data), 
     ), 
    ); 
    $context = stream_context_create($options); 

    $result = file_get_contents($url, false, $context); 

然而在最後一行函數失敗與錯誤failed to open stream: HTTP request failed! HTTP/1.1 403 FORBIDDEN

服務器也發送HTML格式的解釋,但我不知道如何通過file_get_contents訪問它。幫幫我?

編輯:我會用cURL代替。

+3

也許['cURL'](http://php.net/curl)可能是一個更好的解決方案,如果您需要更廣泛的控制情況? – BlitZ 2014-09-04 07:00:47

+0

只是,快速的問題,你的意思是命名'$ data'部分'$ passwort'中的變量還是應該命名爲'$ password'? – Jhecht 2014-09-04 07:04:04

+0

@Jhecht是否重要? 好的,所以我想在使用file_get_contents函數時答案是「這是不可能的」? – Howie 2014-09-04 07:05:12

回答

2

據我所知,這是不可能的。但是如果你使用像Guzzle這樣的HTTP客戶端,你將能夠非常容易地執行這個請求,並且能夠優雅地處理錯誤。 Guzzle也使用cURL,所以你不必直接處理!

發送的POST請求是這樣的:

$client = new GuzzleHttp\Client(); 
$response = $client->post($url, [ 
    'body' => [ 
     'username' => $username, 
     'password' => $password 
    ] 
]); 

echo $response->getStatusCode();   // 200 
echo $response->getHeader('content-type'); // 'application/json; charset=utf8' 
echo $response->getBody();     // {"type":"User"...' 
var_export($response->json());    // Outputs the JSON decoded data 

因爲你把用戶名和密碼的體陣列它會自動URL編碼的!

您將能夠如果響應存在處理錯誤在OO的方式,並得到4XX響應的正文:

try { 
    $client->get('https://github.com/_abc_123_404'); 
} catch (RequestException $e) { 
    echo $e->getRequest(); 
    if ($e->hasResponse()) { 
     echo $e->getResponse(); 
    } 
} 

更多信息,請參見documentation