我正在构建一个基于 Guzzle 的客户端应用程序。我被 cookie 处理困住了。我正在尝试使用 Cookie plugin 来实现它,但我无法让它工作。我的客户端应用程序是标准的 Web 应用程序,只要我使用相同的 guzzle 对象,它看起来就可以正常工作,但跨请求它不会发送正确的 cookie。我正在使用 FileCookieJar
来存储 cookie。如何跨多个 guzzle 对象保存 cookie?
// first request with login works fine
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/123.php?a=b');
// second request where I expect it working, but it's not...
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);
$client->get('/another-test/456');
最佳答案
您正在为第二个请求创建 CookiePlugin
的新实例,您也必须在第二个(和后续)请求中使用第一个实例。
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
//First Request
$client = new Guzzle\Http\Client();
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/first');
//Second Request, same client
// No need for $cookiePlugin = new CookiePlugin(...
$client->get('/test/second');
//Third Request, new client, same cookies
$client2 = new Guzzle\Http\Client();
$client2->addSubscriber($cookiePlugin); //uses same instance
$client2->get('/test/third');
关于php - Guzzle cookies 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15835324/