php - Guzzle cookies 处理

标签 php rest session cookies guzzle

我正在构建一个基于 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/

相关文章:

r - 对 JSON REST API 进行身份验证时如何获取 session token (在 R 中)

javascript - 如何确定 Javascript 中字符串中表达式的类型?

javascript - 从后端获取枚举并将其用作 javascript 中的字符串

python - 在 Django Rest Framework 中测试时获取路由器 url 名称

multithreading - 从数据中获取 session

php - Javascript 函数在我的 Facebook 上基于 iFrame 的应用程序中不起作用/出现错误!

php - 收到警告标题在wordpress上不得包含多个标题

php - MySQL 多个查询不起作用

php - CakePHP模型SQL查询条件参数

php - 如何销毁 Symfony 2 中的所有 session