php 如何使用 Guzzlehttp/guzzle 6 发送 Cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40998662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I send Cookies with Guzzlehttp/guzzle 6?
提问by steve
I need to send a request with custom cookies.
我需要发送带有自定义 cookie 的请求。
I have tried to set cookieJar like this:
我试图像这样设置 cookieJar:
$cookieJar = CookieJar::fromArray(array($cookieName=>$cookieStr),
'api.mobra.in');
$res = $this->guzzleClient->request($requestMethod, $url,
[
'cookies' => [$cookieJar]
]
);
But it is getting an error
但它收到一个错误
cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface
cookie 必须是 GuzzleHttp\Cookie\CookieJarInterface 的一个实例
Please suggest example or explain in details. I gone through documents but they have not mentioned in detail.
请建议示例或详细解释。我浏览了文件,但他们没有详细提及。
Thank you!
谢谢!
回答by Federkun
回答by insign
Guzzlecan maintain a cookie session for you if instructed using the cookies request option. When sending a request, the cookies option must be set to an instance of GuzzleHttp\Cookie\CookieJarInterface
.
如果指示使用 cookie 请求选项,Guzzle可以为您维护 cookie 会话。发送请求时,cookies 选项必须设置为 的实例GuzzleHttp\Cookie\CookieJarInterface
。
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
You can set cookies to true in a client constructor if you would like to use a shared cookie jar for all requests.
如果您想对所有请求使用共享 cookie jar,您可以在客户端构造函数中将 cookie 设置为 true。
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
Check too the full quickstart.
也请查看完整的快速入门。