验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

使用PHP的guzzle怎么添加请求头

阅读:1108 来源:乙速云 作者:代码code

使用PHP的guzzle怎么添加请求头

遇到的问题

我们的一个yii的项目,需要调用一个第三方的接口,这个接口需要请求头需要携带token信息,因此,在发送http请求时,需要在请求头上对应的token。如下图:

使用PHP的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 GuzzleHttpClient;

  $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]);
分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>