Laravel中用GuzzleHttp
今天項目中用到GuzzleHTTP,開始不知道怎么用,其實還是很簡單的。

直接在項目根目錄,輸入以下命令
composer require guzzleHTTP/guzzle
等下載安裝好,在vendor文件夾下,有一個guzzle目錄,此文件夾就是guzzlehttp的package了。
如何使用,可以參考官方文檔http://docs.guzzlephp.org/en/latest/
guzzle中文文檔:http://guzzle-cn.readthedocs.io/zh_CN/latest/overview.html
下面這段代碼就是官網(wǎng)文檔中的一段
$client = new GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // "200" echo $res->getHeader('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // {"type":"User"...' // Send an asynchronous request. $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); $promise = $client->sendAsync($request)->then(function ($response) { echo 'I completed! ' . $response->getBody(); }); $promise->wait();
我在項目中,已經(jīng)使用了form表單post,異步請求等等。
這篇文章還是挺有意思的《Laravel 下使用 Guzzle 編寫多線程爬蟲實戰(zhàn)》,代碼啥都有,雖然是個小玩意,但能學到很多東西。
比如:
在Laravel中如何創(chuàng)建命令
怎么用多線程
貼一下代碼
totalPageCount = count($this->users); $client = new Client(); $requests = function ($total) use ($client) { foreach ($this->users as $key => $user) { $uri = 'https://api.github.com/users/' . $user; yield function() use ($client, $uri) { return $client->getAsync($uri); }; } }; $pool = new Pool($client, $requests($this->totalPageCount), [ 'concurrency' => $this->concurrency, 'fulfilled' => function ($response, $index){ $res = json_decode($response->getBody()->getContents()); $this->info("請求第 $index 個請求,用戶 " . $this->users[$index] . " 的 Github ID 為:" .$res->id); $this->countedAndCheckEnded(); }, 'rejected' => function ($reason, $index){ $this->error("rejected" ); $this->error("rejected reason: " . $reason ); $this->countedAndCheckEnded(); }, ]); // 開始發(fā)送請求 $promise = $pool->promise(); $promise->wait(); } public function countedAndCheckEnded() { if ($this->counter < $this->totalPageCount){ $this->counter++; return; } $this->info("請求結(jié)束!"); } }
運行結(jié)果如下:
$ php artisan test:multithreading-request 請求第 5 個請求,用戶 zhengjinghua 的 Github ID 為:3413430 請求第 6 個請求,用戶 NauxLiu 的 Github ID 為:9570112 請求第 0 個請求,用戶 CycloneAxe 的 Github ID 為:6268176 請求第 1 個請求,用戶 appleboy 的 Github ID 為:21979 請求第 2 個請求,用戶 Aufree 的 Github ID 為:5310542 請求第 3 個請求,用戶 lifesign 的 Github ID 為:2189610 請求第 4 個請求,用戶 overtrue 的 Github ID 為:1472352 請求結(jié)束!
1
HTTP https Laravel
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔相應(yīng)法律責任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔相應(yīng)法律責任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。