一、官网地址
http://docs.guzzlephp.org/en/latest/
二、安装(目前基础框架中已集成)
composer require guzzlehttp/guzzle
三、使用样例
- 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());
- Post请求
$response = $client->request('POST', 'http://httpbin.org/post', [ 'form_params' => [ 'field_name' => 'abc', 'other_field' => '123', 'nested_field' => [ 'nested' => 'hello' ] ] ]);
- 上传文件
$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' ] ] ] ]);
- 存储远程文件
$client = new Client(['verify' => false]); $client->get($fileurl, ['save_to' => $fileFullPath]);
- 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 ]);