2012-02-23 61 views
1

我使用XML API(PHP)做的在線酒店預訂project.When我在預約碼我的工作則顯示以下如何修復411長度file_get_contents和expedia XML API所需的錯誤?

"Warning: file_get_contents(https://[email protected]</email><firstName>test</firstName><lastName>smith</lastName><homePhone>8870606867</homePhone><creditCardType>CA</creditCardType><creditCardNumber>5401999999999999</creditCardNumber>....</HotelRoomReservationRequest>) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 411 Length Required"

其我的代碼

的錯誤
$context = stream_context_create(
       array(
        'http' => array(
         'method' => 'POST', 
         'header' => "Content-type: application/x-www-form-urlencoded", 
         "Accept: application/xml" 
        ) 
       ) 
      ); 
$url ='https://book.api.ean.com/....'; 
$xml = file_get_contents($url, false, $context); 

這是爲了發送信用信息PLZ慈祥地給我建議什麼類型的錯誤......。

+0

您設置流上下文選項的方式有錯誤。 – hakre 2012-02-23 12:13:25

+0

感謝plz提前在我的代碼中提前致謝 – user1117625 2012-02-23 12:16:46

+0

請發佈您的完整代碼。 – hakre 2012-02-23 12:22:46

回答

6

RFC2616 10.4.12

10.4.12 411 Length Required 

    The server refuses to accept the request without a defined Content- 
    Length. The client MAY repeat the request if it adds a valid 
    Content-Length header field containing the length of the message-body 
    in the request message. 

您需要的Content-Length頭添加到您的POST請求。這是POST請求主體的字節大小(八位字節)。要獲得長度,您可以在POST正文上使用strlen。由於您的代碼示例不顯示任何POST正文,因此很難給出具體示例。帖子正文在流上下文中與['http']['content']條目一起傳遞。

如果設置content entry(參見HTTP context options­Docs),可能已經足夠了。

編輯:下面的示例代碼可能解決您的問題。它演示瞭如何使用file_get_contents通過POST請求將一些XML發送到服務器,並設置標題包括Content-Length標題。

$url = 'https://api.example.com/action'; 
$requestXML = '<xml><!-- ... the xml you want to post to the server... --></xml>'; 
$requestHeaders = array(
    'Content-type: application/x-www-form-urlencoded', 
    'Accept: application/xml', 
    sprintf('Content-Length: %d', strlen($requestXML)); 
); 

$context = stream_context_create(
       array(
        'http' => array(
         'method' => 'POST', 
         'header' => implode("\r\n", $requestHeaders), 
         'content' => $requestXML, 
        ) 
       ) 
      ); 
$responseXML = file_get_contents($url, false, $context); 

if (FALSE === $responseXML) 
{ 
    throw new RuntimeException('HTTP request failed.'); 
} 

如果您需要更好的誤差控制,看到ignore_errors HTTP context option­Docs$http_response_header­Docs。 HTTP響應標頭的詳細處理可以在我的博客文章中找到:HEAD first with PHP Streams

+0

如何爲我的代碼做內容長度plz幫助我 – user1117625 2012-02-23 12:14:22

+0

@ user1117625:那麼你需要改變你的代碼,它是不完整的,我不能執行它,所以我無法重現。抱歉。 – hakre 2012-02-23 12:21:01

+1

你甚至讀過什麼? 「內容長度」被提及2次(甚至爲你着色)。它不需要一個天才就能找出該做什麼以及在哪裏投入。人們真的不會努力嘗試找出解決方案嗎? – 2012-02-23 12:21:12

相關問題