pecl_http 在 hotelbeds apitude 中添加 post 请求正文

pecl_http add post request body in hotelbeds apitude

最近我开始使用 hotelbeds apitude PHP API

我正在尝试使用 pecl_httpxml 代码添加到 POST 请求正文中。我尝试使用以下代码 -

$xml_part = <<< EOD
                <<<XML PART>>> EOD;

$request = new http\Client\Request("POST",
                    $endpoint,
                    ["Api-Key" => $hotel_beds_config['api_key'],
                        "X-Signature" => $signature,
                        "Content-Type" => "application/xml",
                        "Accept" => "application/xml"],
                    $xml_part
                );

我收到以下错误

Fatal error: Uncaught TypeError: Argument 4 passed to http\Client\Request::__construct() must be an instance of http\Message\Body, string given

然后我尝试使用以下代码 -

$request = new http\Client\Request("POST",
                    $endpoint,
                    ["Api-Key" => $hotel_beds_config['api_key'],
                        "X-Signature" => $signature,
                        "Content-Type" => "application/xml",
                        "Accept" => "application/xml"],
                    new http\Message\Body($xml_part)

现在我得到以下错误 -

Fatal error: Uncaught http\Exception\InvalidArgumentException: http\Message\Body::__construct() expects parameter 1 to be resource, string given

我得到了在此处添加正文消息的文档 -

pecl_http

如何将 xml 代码添加到 POST 请求?

根据http\Message\Body::__construct() constructor documentation,它可选地接受的单个参数是流或文件句柄资源(如fopen())。它不直接接受您在 $xml_part.

中提供的字符串数据

相反,pecl http 在 Body class 上提供了 an append() method,您应该可以使用它来将 XML 附加到空主体上。因此,首先在变量中创建一个 Body 对象,然后将 XML 附加到它上面。最后,将 Body 对象传递给您的 Request 对象。

// Create a Body object first, with no argument
$body = new http\Message\Body();
// Append your XML to it
$body->append($xml_part);

// Create the Request and pass $body to it
$request = new http\Client\Request("POST",
                $endpoint,
                ["Api-Key" => $hotel_beds_config['api_key'],
                    "X-Signature" => $signature,
                    "Content-Type" => "application/xml",
                    "Accept" => "application/xml"],
                // Pass in $body
                $body
            );

// Create an \http\Client object, enqueue, and send the request...
$client = new \http\Client();
// Set options as needed for your application...
$client->enqueue($request);
$client->send();

附录:为什么不使用 SDK?

您正在尝试 POST 到 provides a PHP SDK 的 API。如果 SDK 支持您希望使用的 Availability 功能,那么使用它可能比 pecl_http(文档有限)更简单。然后,SDK 会将所有 HTTP 消息抽象为一系列 PHP 方法和属性,从而消除对 POST 请求的正确构造的任何疑问。