【问题标题】:guzzle php http client cookies setupguzzle php http 客户端 cookie 设置
【发布时间】:2012-08-17 06:21:19
【问题描述】:

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

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

$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。但我觉得这并不简单,我无法理解它。有人可以帮忙吗??

【问题讨论】:

    标签: symfony cookies guzzle symfony-2.1 zend-http-client


    【解决方案1】:

    或者没有cookie插件

    $client = new HttpClient();
    
    $request = $client->get($url);
    
    foreach($cookies as $name => $value) {
        $request->addCookie($name, $value);
    }
    
    $response = $request->send();
    

    【讨论】:

      【解决方案2】:

      此代码应实现所要求的,即在发出 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();
      

      【讨论】:

      • 我意识到这是一篇旧帖子,但应该注意的是,在此过程中,Guzzle 不会添加新的 cookie,除非它包含有效的域(在此示例中未设置)。这让我很头疼,所以我希望这可以帮助任何有同样问题的人。
      • @NeoNexusDeMortis,如何设置有效域?
      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2014-01-04
      • 1970-01-01
      • 2017-12-14
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      相关资源
      最近更新 更多