耗油饼干处理 [英] Guzzle cookies handling

查看:82
本文介绍了耗油饼干处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于Guzzle构建客户端应用程序.我被cookie处理卡住了.我正在尝试使用 Cookie插件来实现它,但是我无法使其正常工作.我的客户端应用程序是标准的Web应用程序,只要我使用的是相同的guzzle对象,它就可以正常工作,但是在所有请求中,它都不会发送正确的Cookie.我正在使用FileCookieJar来存储cookie.如何将Cookie保留在多个枪口物体上?

I'm building a client app based on Guzzle. I'm getting stucked with cookie handling. I'm trying to implement it using Cookie plugin but I cannot get it to work. My client application is standard web application and it looks like it's working as long as I'm using the same guzzle object, but across requests it doesn't send the right cookies. I'm using FileCookieJar for storing cookies. How can I keep cookies across multiple guzzle objects?

// 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的新实例,还必须在第二个(及后续)请求上使用第一个实例

You are creating a new instance of the CookiePlugin on the second request, you have to use the first one on the second (and subsequent) request as well.

$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');

这篇关于耗油饼干处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆