前言
在服务器登录,有点难度,推荐直接是在本地登录,然后保存cookie
实现代码
$client = new \GuzzleHttp\Client();
$url = 'https://blog.oioweb.cn/';
$jar = new \GuzzleHttp\Cookie\CookieJar();
$domain = 'blog.oioweb.cn';
$cookies = [
'PHPSESSID' => 'web2~ri5m4tjbi6gk6eeu72ghg27l61',
];
$cookieJar = $jar->fromArray($cookies, $domain);
$res = $client->request('GET', $url, [
'cookies' => $cookieJar,
// 'debug' => true,
]);
$body = $res->getBody();
实现代码二
use GuzzleHttp\Cookie\CookieJar;
$cookieJar = CookieJar::fromArray([
'PHPSESSID' => 'b68212de1826c64d77b69dc514c2a9cb'
], 'blog.oioweb.cn'); // 此处记得请求域名需要保持跟请求的url host一致,否则不会携带此cookie。
发送请求携带cookie
$response = $client->request('GET', $url, [
'cookies' => $cookieJar,
]);
设置全局Cookie
设置全局Cookies的以后每次发送请求都会带上此Cookies
$client = new Client([
'cookies' => $cookieJar,
]);