加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

guzzle php http客户端cookie设置

发布时间:2020-12-13 17:42:22 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试从Zend Http Client迁移到Guzzle Http Client.我发现Guzzle功能强大且易于使用,但我认为在使用Cookie插件时没有很好的文档记录.所以我的问题是你如何在Guzzle中为你要针对服务器的HTTP请求设置cookie. 使用Zend Client,你可以做一些简单的事情: $
我正在尝试从Zend Http Client迁移到Guzzle Http Client.我发现Guzzle功能强大且易于使用,但我认为在使用Cookie插件时没有很好的文档记录.所以我的问题是你如何在Guzzle中为你要针对服务器的HTTP请求设置cookie.

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

$client = new HttpClient($url);   // ZendHttpClient 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.但我觉得这不是直截了当的,也无法理解它.可能有人可以帮忙吗?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读