guzzle/guzzle 日常使用

范兴文
2023-12-01

Guzzle

Guzzle 是一个 PHP HTTP 客户端,致力于让发送 HTTP 请求以及与 Web 服务进行交互变得简单。
Github:https://github.com/guzzle/guzzle
Composer:https://packagist.org/packages/guzzlehttp/guzzle

发送请求

use GuzzleHttp\Client;

$client = new Client([
    //跟域名
    'base_uri' => 'http://localhost/test',
    // 超时
    'timeout'  => 2.0,
]);

$response = $client->get('/get'); //http://localhost/get
$response = $client->delete('delete');  //http://localhost/get/delete
$response = $client->head('http://localhost/get');
$response = $client->options('http://localhost/get');
$response = $client->patch('http://localhost/patch');
$response = $client->post('http://localhost/post');
$response = $client->put('http://localhost/put');

POST

$response = $client->request('POST', 'http://localhost/post', [
    'form_params' => [
        'username' => 'webben',
        'password' => '123456',
        'multiple' => [
            'row1' => 'hello'
        ]
    ]
]);

响应

# 状态码
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK

# header
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
    echo "It exists";
}

// Get a header from the response.
echo $response->getHeader('Content-Length');

// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "\r\n";
}

# 响应体
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();

自定义header

// Set various headers on a request
$client->request('GET', '/get', [
	//header
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ],
    //下载
	'save_to'=> $filename,
	//referer
	'allow_redirects' => [
		'referer'		=> '',
	],
]);

cookie 访问

$client = new \GuzzleHttp\Client();

$url = 'https://www.baidu.com/getUserInfo';

$jar = new \GuzzleHttp\Cookie\CookieJar();
$cookie_domain = 'www.baidu.com';
$cookies = [
	'BAIDUID' 	=> '221563C227ADC44DD942FD9E6D577EF2CD',
];

$cookieJar = $jar->fromArray($cookies, $cookie_domain);

$res = $client->request('GET', $url, [
       'cookies' => $cookieJar,
       // 'debug' => true,
]);
$body = $res->getBody();

手册地址:http://docs.guzzlephp.org/en/stable/request-options.html#headers

爬虫脚本

include './vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;

class Metting{

    private $client;
    /**
     * 可以有多个候选,防止会议室被提前预定。
     * 预定成功自动break
     **/
    public $rooms = [
        195 => '阿基米德',
        196 => '费曼',
        203 => '特斯拉',
        202 => '爱因斯坦',
        188 => '牛顿',
    ];
    public $time_start  = '15:00';
    public $time_end    = '16:30';

    /**
     * tip 从Charles复制过来的是utf8需要转码
     **/
    private $cookies = [
        'xdf_openid'  => 'ktxPYw7mXiAFvoTno8yIVZUXo7FkahPMQMpXvqrH0q0=',
    ];

    public $base_uri        = 'http://smr.xdf.cc/';
    public $submit_uri      = '/bespoke/Bespoke/addSaveAPP/';
    public $lock_uri        = '/bespokepc/Index/addSavePCMeeting/';
    public $cookie_domain   = 'smr.xdf.cc';
    // 员工ID
    public $staffid         = 10000;
    //public $base_uri      = 'http://127.0.0.1:1999/';
    //public $lock_uri      = '/metting/lock';
    //public $submit_uri    = '/metting/submit';
    //public $cookie_domain = '127.0.0.1:1999';

    public function __construct()
    {
        $cookieJar = CookieJar::fromArray( $this->cookies, $this->cookie_domain);
        $this->client = new Client([
            'base_uri'  => $this->base_uri,
            'timeout'   => 5,
            'cookies'    => $cookieJar,
            'headers'    => [
                'User-Agent' => $this->user_agent,
            ],
        ]);
    }

    public function run(){
        $day = date('Y-m-d',strtotime('+1 day'));
        foreach( $this->rooms as $roomid => $roomname){
            $lockid = $this->lock( $roomid, $day);
            if( $lockid > 0){
                $ret = $this->submit( $lockid, $roomid, $day);
                if( $ret){
                    break;
                }
            }
            usleep(10*1000);
        }
    }

    /**
     * 锁定成功返回lockid,失败(被别人预定)为0,有其他异常可能未处理
     * lock 接口未限制权限,也可以用postman模拟
     **/
    public function lock( $roomid, $day){
        //$uri = '/metting/lock';
        $data = [
            'day'       => $day,
            'start'     => $this->time_start,
            'end'       => $this->time_end,
            'roomid'    => $roomid,
        ];
        print_r( $data);
        $resp = $this->client->request('POST', $this->lock_uri,[
            'form_params' => $data
        ]);
        $body = (string) $resp->getBody();
        return $body;
    }

    public function submit( $lockid, $roomid, $day){
        //$uri = '/metting/submit';
        $data = [
            'theme'         => '研发周会',
            'content'       => '',
            'renshu'        => 1,
            'emailstr'      => '',
            'mail_rili'     => [0 => 1, 1=>1],
            'canjiaemail'   => '',
            'canjiastaff1'  => '',
            'canjiastaff'   => $this->staffid,
            'appointID'     => 0,
            'roomid'        => $roomid,
            'appORweb'      => 0,
            'keyuyue'       => $this->time_start.'~'.$this->time_end,
            'day'           => $day,
            'urgent'        => 0,
            'meetID'        => $lockid
        ];
        $resp = $this->client->request('POST', $this->submit_uri, [
            'form_params' => $data
        ]);
        print_r( $data);
        $body = $resp->getBody()->getContents();
        print_r( $body);
        $array = json_decode( $body, true);
        print_r( $array);
        if( $array['ed4'] == 200){
            return true;
        }
        return false;
    }
    private $user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/18D52 AliApp(DingTalk/6.0.10) com.laiwang.DingTalk/14684863 Channel/201200 language/zh-Hans-CN UT4Aplus/0.0.6 WK';
}
$obj = new Metting();
$obj->run();
 类似资料: