协程(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);
});