kri*_*hna 4 cookies httpclient symfony zend-http-client symfony-2.1
我正在尝试从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
Run Code Online (Sandbox Code Playgroud)
那么,你如何在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
Run Code Online (Sandbox Code Playgroud)
当响应从具有set-cookie标头的服务器返回时,您可以在$ cookieJar中获得这些cookie.
Cookie jar也可以从CookiePlugin方法获得
$cookiePlugin->getCookieJar();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6227 次 |
| 最近记录: |