2012-07-03 74 views
14

我想POST JSON內容到遠程REST端點發布JSON,但是「內容」值似乎是交付空。所有其他頭文件等正在被正確接收,並且Web服務使用基於瀏覽器的測試客戶端成功測試。PHP - 通過的file_get_contents

有沒有下面,我指定「內容」字段我的語法有問題?

$data = array("username" => "duser", "firstname" => "Demo", "surname" => "User", "email" => "[email protected]"); 
$data_string = json_encode($data); 

$result = file_get_contents('http://test.com/api/user/create', null, stream_context_create(array(
'http' => array(
'method' => 'POST', 
'header' => array('Content-Type: application/json'."\r\n" 
. 'Authorization: username:key'."\r\n" 
. 'Content-Length: ' . strlen($data_string) . "\r\n"), 
'content' => $data_string) 
) 
)); 

echo $result; 

回答

16

這是我一直使用的代碼,它看起來很相似(儘管這當然是x-www-form-urlencoded)。 也許你username:key需求是base64_encode「d。

function file_post_contents($url, $data, $username = null, $password = null) 
{ 
    $postdata = http_build_query($data); 

    $opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => 'Content-type: application/x-www-form-urlencoded', 
      'content' => $postdata 
     ) 
    ); 

    if($username && $password) 
    { 
     $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password")); 
    } 

    $context = stream_context_create($opts); 
    return file_get_contents($url, false, $context); 
} 
+1

由於,這工作很好! – Ben

+4

如果某人運行到該POSTDATA的編碼不正確的問題(字典的每個鍵具有「安培;」開頭): 第三行更改爲$ POSTDATA = http_build_query($數據,' ','&'); – Philipp

3

function file_post_contents($url, $data, $username = null, $password = null) { 
$postdata = http_build_query($data); 

$opts = array('http' => 
    array(
     'method' => 'POST', 
     'header' => 'Content-type: application/x-www-form-urlencoded', 
     'content' => $postdata 
    ) 
); 

if($username && $password) 
{ 
    $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password")); 
} 

$context = stream_context_create($opts); 
return file_get_contents($url, false, $context);} 

較早的響應不正確。此功能有時,但它是不準確的,如果你不使用的內容類型的application/x-WWW窗體-urlencoded將失敗和你在一個用戶名和密碼通過。

它的工作的作家,因爲應用程序/ x-WWW窗體-urlencoded是默認的內容類型,但是他處理的用戶名和密碼被覆蓋的內容類型的早期聲明。

這裏是校正函數:

function file_post_contents($url, $data, $username = null, $password = null){ 
$postdata = http_build_query($data); 

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

if($username && $password) 
{ 
    $opts['http']['header'] .= ("Authorization: Basic " . base64_encode("$username:$password")); // .= to append to the header array element 
} 

$context = stream_context_create($opts); 
return file_get_contents($url, false, $context);} 

注行: $ OPTS [ 'HTTP'] [ '標題'=(。點等於追加到數組元素)