如何使用file_get_contents和expedia XML API修复411 Length Required错误?

时间:2012-02-23 11:59:51

标签: php xml api http

我正在使用xml api(php)项目进行在线酒店预订。当我在预订代码中工作时,它显示以下错误

  

"Warning: file_get_contents(https://...@gmail.com</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请给我建议什么类型的错误......

1 个答案:

答案 0 :(得分: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