6

我正在构建一个基于 Guzzle 的客户端应用程序。我被 cookie 处理困住了。我正在尝试使用Cookie 插件来实现它,但我无法让它工作。我的客户端应用程序是标准的 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');
4

3 回答 3

5

您正在创建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');
于 2013-09-09T22:22:32.777 回答
3
$cookiePlugin = new CookiePlugin(new FileCookieJar($cookie_file_name));

// Add the cookie plugin to a client
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);

// Send the request with no cookies and parse the returned cookies
$client->get($domain)->send();

// Send the request again, noticing that cookies are being sent
$request = $client->get($domain);
$request->send();

print_r ($request->getCookies());
于 2013-04-18T19:12:45.643 回答
3

如果所有请求都在同一个用户请求中完成,则当前答案将起作用。但是,如果用户先登录,然后浏览该站点并稍后再次查询“域”,则它将不起作用。

这是我的解决方案(使用 ArrayCookieJar()):

登录

$cookiePlugin = new CookiePlugin(new ArrayCookieJar());

//First Request
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);
$request = $client->post('/login');
$response = $request->send();

// Retrieve the cookie to save it somehow
$cookiesArray = $cookiePlugin->getCookieJar()->all($domain);
$cookie = $cookiesArray[0]->toArray();

// Save in session or cache of your app.
// In example laravel:
Cache::put('cookie', $cookie, 30);

其他要求

// Create a new client object
$client = new Client($domain);
// Get the previously stored cookie
// Here example for laravel
$cookie = Cache::get('cookie');
// Create the new CookiePlugin object
$cookie = new Cookie($cookie);
$cookieJar = new ArrayCookieJar();
$cookieJar->add($cookie);
$cookiePlugin = new CookiePlugin($cookieJar);
$client->addSubscriber($cookiePlugin);

// Then you can do other query with these cookie
$request = $client->get('/getData');
$response = $request->send();

于 2014-09-09T12:29:30.017 回答