我怎样才能在pecl_http库中使用post请求

时间:2016-05-29 14:46:06

标签: httprequest pecl

hotelbeds api

api需要在一些字段中使用post请求,但我不知道字段将被添加到哪里!! (在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说

  

下面列出了搜索的可用过滤器。

     

它包含一个具有以下结构的过滤器数组:

     

[{&#34; searchFilterItems&#34;:[{&#34; type&#34;:&#34; destination&#34;,&#34; value&#34;:&#34; BCN&#34 ;}]}]

     

对象“searchFilterItems”包含以下属性:type&gt;和价值。

     

以下示例说明了&gt;的不同类型和值。每个过滤器:

     

国家

     

{&#34; type&#34;:&#34; country&#34;,&#34; value&#34;:&#34; PT&#34;}

2 个答案:

答案 0 :(得分:2)

我有同样的问题,花了一点时间弄明白。事实证明,您需要使用Body类来表示发布数据。

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

Message和Body类中还有一些方法可用于包含文件等。

答案 1 :(得分:1)

试试这种方式

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