PHP大道至简之swoole请求必应壁纸

本文介绍了如何使用PHP的swoole库进行Http2请求接口和下载图片,通过协程实现高效率操作,避免了curl封装,提升了性能。
摘要由CSDN通过智能技术生成

协程(Coroutine)

Http2请求接口

代码如下:

	$client = new Swoole\Coroutine\Http2\Client($domain, 443, true);
    //设置超时、ssl
    $client->set([
        'timeout' => -1,
        'ssl_host_name' => $domain,
    ]);
    //connect
    $client->connect();
    //实例化 request请求
    $req = new swoole_http2_request;
    //请求方式
    $req->method = 'GET';
    //请求地址
    $req->path = '/HPImageArchive.aspx?format=js&idx=0&n=1';
    //设置header头
    $req->headers =$head;
    //发送请求
    $client->send($req);
    //接收返回的response
    $response = $client->recv();
    //关闭连接
    $client->close();

Http下载图片

代码如下:

	$cli = new \Swoole\Coroutine\Http\Client($domain, 443, true);
    //长连接
    $cli->set(['timeout' => -1]);
    //设置header头部
    $cli->setHeaders($head);
    //下载图片
    $cli->download($imageUrl, './wallpaper/'.$imageTile.date('Y-m-d').'.jpg',0);

代码如下:

swoole请求需要调用自身的http、http2完成。可以省去封装curl,并且效率更高。

//协程
go(function(){
    //请求域名
    $domain = 'cn.bing.com';
    //header信息
    $head = [
        'host'=>$domain,
        'accept-encoding'=>'gzip, deflate',
        'accept-language'=>'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'user-agent'=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36 Edg/79.0.309.54',
    ];
    //请求服务器
    $client = new Swoole\Coroutine\Http2\Client($domain, 443, true);
    //设置超时、ssl
    $client->set([
        'timeout' => -1,
        'ssl_host_name' => $domain,
    ]);
    //connect
    $client->connect();
    //实例化 request请求
    $req = new swoole_http2_request;
    //请求方式
    $req->method = 'GET';
    //请求地址
    $req->path = '/HPImageArchive.aspx?format=js&idx=0&n=1';
    //设置header头
    $req->headers =$head;
    //发送请求
    $client->send($req);
    //接收返回的response
    $response = $client->recv();
    //关闭连接
    $client->close();
    //decode
    $image = json_decode($response->data,true);
    //壁纸
    $imageUrl = substr($image['images'][0]['url'],0,-7);
    $imageTile = substr($image['images'][0]['copyright'],0,stripos($image['images'][0]['copyright'],'('));
    //download image
    $cli = new \Swoole\Coroutine\Http\Client($domain, 443, true);
    //长连接
    $cli->set(['timeout' => -1]);
    //设置header头部
    $cli->setHeaders($head);
    //下载图片
    $cli->download($imageUrl, './wallpaper/'.$imageTile.date('Y-m-d').'.jpg',0);

});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值