簡體   English   中英

pecl_http在hotelbeds apitude中添加帖子請求正文

[英]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
                );

我收到以下錯誤

致命錯誤:未捕獲TypeError:傳遞給http \\ Client \\ Request :: __ construct()的參數4必須是http \\ Message \\ Body的實例,給出字符串

然后我嘗試使用以下代碼 -

$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)

現在我得到以下錯誤 -

致命錯誤:未捕獲http \\ Exception \\ InvalidArgumentException:http \\ Message \\ Body :: __ construct()期望參數1為資源,給定字符串

我在這里獲得了添加正文消息的文檔 -

pecl_http

如何將xml代碼添加到POST請求中?

根據http\\Message\\Body::__construct()構造函數文檔 ,它可選擇接受的單個參數是流或文件句柄資源(如fopen() )。 它不像您在$xml_part提供的那樣直接接受字符串數據。

相反,pecl http在Body類上提供了一個append()方法 ,您應該可以使用該方法將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的API 提供了PHP SDK 如果SDK支持您希望使用的可用性功能,那么使用它可能更簡單,而不是pecl_http(其文檔有限)。 然后,SDK會將所有HTTP消息傳遞抽象為一系列PHP方法和屬性,從而消除對正確構造POST請求的任何疑問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM