guzzle php http客户端cookies设置
我正在尝试从Zend Http客户端迁移到Guzzle Http客户端。我发现Guzzle的功能很好,大部分都很容易使用,但我认为它在使用Cookie插件时没有很好的文档记录。所以我的问题是,如何在Guzzle中为针对服务器发出的HTTP请求设置cookie 使用Zend Client,您可以执行以下简单操作:guzzle php http客户端cookies设置,cookies,symfony,httpclient,symfony-2.1,zend-http-client,Cookies,Symfony,Httpclient,Symfony 2.1,Zend Http Client,我正在尝试从Zend Http客户端迁移到Guzzle Http客户端。我发现Guzzle的功能很好,大部分都很容易使用,但我认为它在使用Cookie插件时没有很好的文档记录。所以我的问题是,如何在Guzzle中为针对服务器发出的HTTP请求设置cookie 使用Zend Client,您可以执行以下简单操作: $client = new HttpClient($url); // Zend\Http\Client http client object instantiation $cooki
$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客户端请求之前,在请求上设置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();
或者没有cookie插件
$client = new HttpClient();
$request = $client->get($url);
foreach($cookies as $name => $value) {
$request->addCookie($name, $value);
}
$response = $request->send();
我知道这是一篇老文章,但应该注意的是,Guzzle不会在某个地方添加新的cookie,除非它包含一个有效的域(本例中没有设置)。这给我带来了很多麻烦,所以我希望这能帮助任何和我有同样问题的人。@NeoNexusDeMortis,以及如何设置有效域?