4

我正在尝试从 Zend Http Client 迁移到 Guzzle Http Client。我发现 Guzzle 的功能很好并且在大多数情况下易于使用,但我认为在使用 Cookie 插件时没有很好的文档记录。所以我的问题是如何在 Guzzle 中为要对服务器发出的 HTTP 请求设置 cookie。

使用 Zend Client,您可以做一些简单的事情:

$client = new HttpClient($url);   // Zend\Http\Client http client object instantiation
$cookies = $request->cookies->all();   // $request Symfony request object that gets all the cookies, as array name-value pairs, that are set on the end client (browser) 
$client->setCookies($cookies);  // we use the above client side cookies to set them on the HttpClient object and,
$client->send();   //finally make request to the server at $url that receives the cookie data

那么,你如何在 Guzzle 中做到这一点。我看过http://guzzlephp.org/guide/plugins.html#cookie-session-plugin。但我觉得这并不简单,我无法理解它。可能有人可以帮忙吗?

4

2 回答 2

5

此代码应实现所要求的,即在发出 guzzle 客户端请求之前在请求上设置 cookie

$cookieJar = new ArrayCookieJar();  // new jar instance
$cookies = $request->cookies->all(); // get cookies from symfony symfony Request instance
foreach($cookies as $name=>$value) {  //create cookie object and add to jar
  $cookieJar->add(new Cookie(array('name'=>$name, 'value'=>$value)));
}

$client = new HttpClient("http://yourhosturl");
$cookiePlugin = new CookiePlugin($cookieJar);

// Add the cookie plugin to the client object
$client->addSubscriber($cookiePlugin);

$gRequest = $client->get('/your/path');

$gResponse = $gRequest->send();      // finally, send the client request

当响应从带有 set-cookie 标头的服务器返回时,您可以在 $cookieJar 中使用这些 cookie。

Cookie jar 也可以从 CookiePlugin 方法中获取

$cookiePlugin->getCookieJar();
于 2012-08-21T23:33:01.590 回答
2

或者没有 cookie 插件

$client = new HttpClient();

$request = $client->get($url);

foreach($cookies as $name => $value) {
    $request->addCookie($name, $value);
}

$response = $request->send();
于 2014-04-17T08:48:17.423 回答