Guzzle HTTP使用笔记

首先来一段官方文档对Guzzle的介绍:

Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

  • 接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
  • 发送同步或异步的请求均使用相同的接口。
  • 使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。
  • 抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。
  • 中间件系统允许你创建构成客户端行为。

执行Composer命令下载Guzzle:Linux环境、Windows都一样

composer require guzzlehttp/guzzle

下载完成后会生成一个vender文件夹:

我这边使用的Tp5框架进行开发。

因为Guzzle属于PHP的第三方扩展,所以使用前先  use引用  接着实例化*******

<?php
namespace app\admin\controller;

use app\admin\controller\BasicAdmin;
use app\admin\service\DataService;
use GuzzleHttp\Client;
use think\Db;

class News extends BasicAdmin
{//企业微信推送消息
    public function send_message()
    {
        //实例化 GuzzleHttp
        $client = new Client();
        //文章id
        $news_id = input('news_id');
        //查询文章
        $news_data = Db::table('wm_news')->where('id',$news_id)->find();
        //企业微信参数
        $corpid = "*************";
        $secret = "*********";
        //先通过token获取 access_token
        $access_token = cookie('access_token');
        //如果access_token为空,则去获取,存储
//如果推送的消息没有图片则给一张企业默认图片
if (empty($news_data['img_url'])) { $news_data['img_url'] = 'https://tcms.living-power.com/static/images/common/lingpa.jpg'; } if (empty($access_token)) { $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$corpid."&corpsecret=".$secret; $response = $client->request('GET',$url); $body = $response->getBody();//获取相应体 $html = $body->getContents();//获取目标页面 //解密json字符串 $res = json_decode($html,true); //存储access_token $access_token = $res['access_token']; } $agentid = "1000002"; //推送消息 //如果推送的消息没有图片则给一张企业默认图片 if (empty($news_data['img_url'])) { $news_data['img_url'] = 'http://cms.living-power.com/static/images/common/lingpa.jpg'; } $msgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$access_token; $send_msg['touser'] = '@all'; $send_msg['msgtype'] = 'news'; $send_msg['agentid'] = $agentid; $send_msg['news']['articles'][0]['title'] = $news_data['title']; $send_msg['news']['articles'][0]['description'] = strip_tags($news_data['content']); $send_msg['news']['articles'][0]['url'] = 'https://tqymobile.living-power.com/index.php/blog/news/detail?id='.$news_id; $send_msg['news']['articles'][0]['picurl'] = $news_data['img_url']; $send_msg['safe'] = 0; //$send_msg = json_encode($send_msg); $response = $client->request('POST',$msgUrl,['json' => $send_msg]); $body = $response->getBody();//获取相应体 $html = $body->getContents();//获取目标页面 //解密json字符串 $res = json_decode($html,true); // print_r($res);die(); } }

具体参考文档:https://guzzle-cn.readthedocs.io/zh_CN/latest/

猜你喜欢

转载自www.cnblogs.com/T8888/p/12746502.html
今日推荐