关于GuzzleHttp/Client的使用分享

介绍:

   Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上.

安装:

    composer require guzzlehttp/guzzle

基础:

    use GuzzleHttp\Client;

    $client = new Client();

    $request = $client->request('GET', 'https://www.google.com/');

    $headers = $request->getHeaders();

    $contents = $request->getBody()->getContents();

进阶:

    模拟POST提交表单

    $options = [

        'form_params' => [

            'username' => 'zhangsan',

            'password' => '123456'

        ]

    ];

    $client->request('POST', 'https://www.google.com/', $options);

    自定义headers进行请求

    $options = [

        'headers' => [

            'Authorization' => 'access_token',

            'user-agent' => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',

            'x-requested-with' => 'XMLHttpRequest'

        ];

    ];

    $client->request('POST', 'https://www.google.com/', $options);

    携带cookie进行请求:

    use GuzzleHttp\Cookie\CookieJar;

    $jar = new CookieJar();

    $cookies = [

        'sessionid' => 'sessionid',

        'user_id=' => 'user_id'

    ];

    $jar->fromArray($cookies, 'https://www.google.com/');

    $options = [

        'cookies' => $jar;

    ];

    $client->request('POST', 'https://www.google.com/', $options);

文档地址:https://docs.guzzlephp.org/en/stable/index.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容