天天看點

使用PHP的http請求用戶端guzzle如何添加請求頭

一.目錄

  1. 遇到的問題
  2. guzzle基礎知識
  3. 添加請求頭的兩種方式

二.遇到的問題

我們的一個yii的項目,需要調用一個第三方的接口,這個接口需要請求頭需要攜帶token資訊,是以,在發送http請求時,需要在請求頭上對應的token。如下圖:

使用PHP的http請求用戶端guzzle如何添加請求頭

我們的項目請求第三方,使用的是guzzle元件,做了記錄,以防以後查詢使用

三.guzzle基礎知識

Guzzle是一個使得利用PHP實作發送HTTP 請求,友善和web service內建的PHP 用戶端模拟元件。

Guzzle介紹

簡單的接口建構query string,POST requests,streaming large uploads/downloads,使用HTTP cookies,上傳json data等。

可以使用相同的接口來發送同步和異步的請求。

使用PSR-7 interface for requests, response,stream.這允許你使用其他的PSR-7相容的庫和Guzzle一起工作

将底層的HTTP傳輸層抽象屏蔽,允許你編寫環境和傳輸協定無關的代碼,即:再也沒有對cURL,PHP streams, sockets,或者non-blocking event loops強依賴的代碼。

中間件系統允許你增強你的用戶端行為。

Post/Get請求

發送請求前,我們需要執行個體化本地下載下傳的guzzle
  use GuzzleHttp\Client;

  $client = new Client([
      //跟域名
      'base_uri' => 'http://localhost/test',
      // 逾時,可設定可不設定
      'timeout'  => 2.0,
  ]);
  post請求
    $response = $client->request('POST', 'http://localhost/post', [
      'form_params' => [
          'username' => 'webben',
          'password' => '123456',
          'multiple' => [
              'row1' => 'hello'
           ]
       ]
    ]);
  get請求
    $response = $client->request('POST', 'http://localhost/post', [
        'query' => [
            'username' => 'webben',
            'password' => '123456',
        ]
    ]);
  或者
    $response = $client->POST/GET('http://localhost/post', [
        'form_params' => [
            'username' => 'webben',
            'password' => '123456',
            'multiple' => [
                'row1' => 'hello'
            ]
        ]
    ]);
      

自定義header

$client = new Client([
        //域名或者通路的api接口位址
        'base_uri' => 'http://localhost/test',
        // 逾時,可設定可不設定
        'timeout'  => 2.0,
    ]);
// $api可以為空,一般為api接口字尾,也可以直接寫到上面的base_uri裡面,
$response = $client->request('POST/GET', '$api', [
    'headers' => [
           'name' => 'info'
       ],
      'query' => [
          'username' => 'webben',
          'password' => '123456',
      ]
  ]);
      

四.添加請求頭的兩種方式

如何要發送一個POST請求,并且需要添加header頭,而且post的資料是json格式,有兩種方式

postData是一個數組:

$postData = [
            'platform_no'=> $rms_platform_no,
            'uuid' => $uuid,
            "data_info" => $param
        ];      
$rs =  $this->http($url , 'POST' , ['headers'=>$headers,'body'=>json_encode($postData)]);      
$rs =  $this->http($url , 'POST' , ['headers'=>$headers,'json'=>$postData]);