如何配置 Goutte Client 使用文件将 cookie 存储在文件中?我知道它是一种围绕 GuzzleHttp 客户端的包装器。但我无法将其配置为将 cookie 保存到文件中以在请求之间重用它们。
尝试扩展 Goutte 客户端,doRequest
方法,但我不明白如何正确执行此操作。
有没有人用过 Goutte Client 把 cookie 保存到文件?
最佳答案
我认为没有一种简单的方法可以实现这一点,因为 Goutte 强制使用 guzzle 的 CookieJar 类,该类在脚本执行后不会持续存在。通过你自己的类(class)来使用像 FileCookieJar 这样的东西会很棒但是由于硬编码的 CookieJar 调用,这是不可能的(有人确实为它创建了一个 PR 但是现在已经几个月了而且最近没有任何事件在里面Goutte 项目)。
我们可以做的是创建访问 BrowserKit CookieJar 并存储其内容的方法。下面是一些示例代码:
// Will hold path to a writable location/file
protected $cookieFilePath;
public function setCookieFilePath($cookieFilePath)
{
$this->cookieFilePath = $cookieFilePath;
if (is_file($cookieFilePath)) {
// Load cookies and populate browserkit's cookie jar
$cookieJar = $this->client->getCookieJar();
$cookies = unserialize(file_get_contents($cookie));
foreach ($cookies as $cookie) {
$cookieJar->set($cookie);
}
}
}
// Call this whenever you need to save cookies. Maybe after a request has been made since BrowserKit repopulates it's CookieJar from the Response returned.
protected function saveCookies()
{
$cookieFilePath = $this->getCookieFilePath();
$goutteClient = $this->getGoutteClient();
$cookieJar = $goutteClient->getCookieJar();
$cookies = $cookieJar->all();
if ($cookies) {
file_put_contents($cookieFilePath, serialize($cookies));
}
}
https://stackoverflow.com/questions/32936480/