Search code examples
httprequestpecl

How can i use post request in pecl_http library


hotelbeds api

The api required to use post request with some fields, but i don't know where are the fields will be added!! ( in GET request i add the fields in the url like any request )

the api code

`

$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>";

the api said

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"}


Solution

  • I had the same issue, took me a little while to figure it out. Turns out you need to use the Body class to represent the post data.

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

    There are some more methods available in the Message and Body class for including files, etc.