我如何在 pecl_http 库中使用 post 请求

How can i use post request in pecl_http library

hotelbeds api

使用post请求某些字段需要api,但我不知道这些字段将被添加到哪里!! (在 GET 请求中,我像任何请求一样在 url 中添加字段)

api代码

`

$apiKey = "8z8a7tupn5hubhjxqh8ubuz7";
$sharedSecret = "jsSJq2msbU";
$signature = hash("sha256", $apiKey.$sharedSecret.time());

$endpoint = "https://api.test.hotelbeds.com/activity-api/3.0/activities";

$request = new \http\Client\Request("POST",
    $endpoint,
    [ "Api-Key"     => $apiKey,
    "X-Signature" => $signature,
    "Accept"      => "application/json" ,
    ]);


$client = new \http\Client;

$client->enqueue($request)->send();

$response = $client->getResponse();

    echo "<pre>";
    print_r($response->getBody());
    echo "</pre>";

api 说

The available filters for the search is listed below.

It contains an array of filter with the following structure:

[{"searchFilterItems": [{"type": "destination", "value": "BCN"}]}]

The Object “searchFilterItems” contains the following attributes: type > and value.

The following examples illustrate the different types and values for > each filter:

Country

{"type": "country", "value": "PT"}

我遇到了同样的问题,我花了一点时间才弄明白。结果你需要使用 Body class 来表示 post 数据。

$msg = new http\Message\Body();
$msg->addForm([
  'field1' => 'value',
  'field2' => 'value2'
]);

$headers = null;

$request = new http\Client\Request('POST', 'https://example.com', $headers, $msg);

$client = new http\Client();
$client->enqueue($request);
$client->send();

$response = $client->getResponse();

消息和正文中还有一些方法可用 class 用于包含文件等。

试试这个方法

$request = new http\Client\Request;
            $body = new http\Message\Body;
            $body->append('{Your JSON}');
            $request->setRequestUrl('https://api.hotelbeds.com/hotel-api/1.0 hotels');
            $request->setRequestMethod('POST');
            $request->setBody($body);
            $request->setHeaders(array(
                'Accept'                        => 'application/json',
                'Content-Type'          => 'application/json',
                'Api-Key'               => $owapiKey,
                'X-Signature'               => $signature,
              //'Accept-Encoding'   => 'Gzip',  //Deflate
              'cache-control'       => 'no-cache'
            ));

            try {
                $client = new http\Client;
                $client->enqueue($request)->send();
                $response = $client->getResponse();

                if ($response->getResponseCode() != 200) {  
                echo("HTTP CONNECT FAILURE: -> ".
                $response->getTransferInfo("effective_url").
                $response->getInfo().$response->getResponseCode() );
            } else {
                            $res=$response->getBody()->toString();
                         }              

            } catch (Exception $ex) { echo("Error while sending request, reason: %s\n".$ex->getMessage()); }