[ laravel爬虫实战--基础篇 ] guzzle发送异步请求

Song5214 次浏览0个评论2017年11月01日

同步请求是指,发送方发出数据后,等接收方发回响应以后才发下一个数据包的通讯方式。异步请求是指,发送方发出数据后,不等接收方发回响应,接着发送下个数据包的通讯方式。

我们可以使用Client提供的方法来创建异步请求, 这样我们就不用等待返回就继续执行后续的操作:

$promise = $client->getAsync(http://httpbin.org/get);
$promise = $client->deleteAsync(http://httpbin.org/delete);
$promise = $client->headAsync(http://httpbin.org/get);
$promise = $client->optionsAsync(http://httpbin.org/get);
$promise = $client->patchAsync(http://httpbin.org/patch);
$promise = $client->postAsync(http://httpbin.org/post);
$promise = $client->putAsync(http://httpbin.org/put);

你也可以使用ClientsendAsync()requestAsync()方法:

<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
class TestController extends Controller
{
    public function test()
    {
        $client = new Client([base_uri => https://baidu.com/]);
        $headers = [X-Foo => Bar];
        $body = Hello!;
        $request = new Request(HEAD, http://baidu.com/, $headers, $body);
        $promise = $client->requestAsync(GET, http://baidu.com/);
        dd($request);
        dd($promise);
}
}

这些方法返回了RequestPromise对象,该对象实现了由Guzzle promises library提供的Promises/A+ spec,这意味着你可以使用then()来调用返回值,成功使用Psr\Http\Message\ResponseInterface处理器,否则抛出一个异常。

<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Console\Command;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
class TestController extends Controller
{
    public function test()
    {
        $client = new Client([base_uri => https://baidu.com/]);
        $promise = $client->requestAsync(GET, https://baidu.com/);
        $promise->then(
            function (ResponseInterface $res) {
                echo $res->getStatusCode() . "\n";
            },
            function (RequestException $e) {
                echo $e->getMessage() . "\n";
                echo $e->getRequest()->getMethod();
            }
        );
        dd($promise);
}
}

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文