Laravel实用工具介绍 – Guzzle

一、官网地址

http://docs.guzzlephp.org/en/latest/

二、安装(目前基础框架中已集成)

composer require guzzlehttp/guzzle

三、使用样例

  1. Get请求
    $client = new Client();
    $request = $client->request('GET', 'https://api.weixin.qq.com/sns/oauth2/access_token', [
    	'query' => [
    		'appid' => $this->wxappid,
    		'secret' => $this->wxappsecret,
    		'code' => request('code'),
    		'grant_type' => 'authorization_code'
    	]
    ]);
    $wxresult = json_decode($request->getBody()->getContents());

     

  2. Post请求
    $response = $client->request('POST', 'http://httpbin.org/post', [
        'form_params' => [
            'field_name' => 'abc',
            'other_field' => '123',
            'nested_field' => [
                'nested' => 'hello'
            ]
        ]
    ]);

     

  3. 上传文件
    $response = $client->request('POST', 'http://httpbin.org/post', [
        'multipart' => [
            [
                'name'     => 'field_name',
                'contents' => 'abc'
            ],
            [
                'name'     => 'file_name',
                'contents' => fopen('/path/to/file', 'r')
            ],
            [
                'name'     => 'other_file',
                'contents' => 'hello',
                'filename' => 'filename.txt',
                'headers'  => [
                    'X-Foo' => 'this is an extra header to include'
                ]
            ]
        ]
    ]);

     

  4. 存储远程文件
    $client = new Client(['verify' => false]);
    $client->get($fileurl, ['save_to' => $fileFullPath]);

     

  5. cookie操作
    $http = new \GuzzleHttp\Client([
    	'base_uri' => 'http://' . FACE_DOMAIN,
    	'connect_timeout' => 2,
    	'timeout' => 2
    ]);
    
    $request = $http->post('auth/login', [
    	'headers' => [
    		'User-Agent' => 'Koala Admin',
    	],
    	'form_params' => [
    		'username' => FACE_USERNAME,
    		'password' => FACE_PASSWORD
    	]
    ]);
    
    $cookie_array = $request->getHeader('Set-Cookie');
    $logincookie = '';
    if (isset($cookie_array[0])) {
    	$logincookie = substr($cookie_array[0], strpos($cookie_array[0], 'session=') + 8, strpos($cookie_array[0], ';') - 8);
    }
    
    $face_cookiejar = new CookieJar(false, [
    	[
    		'Name' => 'session',
    		'Value' => $face_logincookie,
    		'Domain' => FACE_DOMAIN,
    		'HttpOnly' => true
    	]
    ]);
    
    $http->delete("subject/{$subject_id}", [
    	'cookies' => $face_cookiejar
    ]);

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值