我正在使用Guzzle登录我的API网站,并且在我使用正确的凭据登录的那一刻,我回来了一个带有RefreshToken的cookie,以便在下次调用时发送它,这是我的简单(并且正常工作)好)代码:
var items = [];
if (map == "checked") {
items.push("map");
alert("map ok")
}
if (joueurs == "ckecked") {
items.push("player");
alert("joueurs ok")
}
if (point == "checked") {
items.push("point");
alert("points ok")
}
if(items.length > 0){
var message = items.join(" ") + "ok";
alert(message);
}
我用cookie回复正确的回复,我可以通过使用
看到cookievar mask = 0;
if (map == "checked") {
mask += 1;
alert("map ok");
}
if (joueurs == "ckecked") {
mask += 2;
alert("joueurs ok");
}
if (point == "checked") {
mask +=4;
alert("points ok");
}
if(mask == 7){
alert("map player point ok");
}
else if (mask == 3){
alert("player map ok");
}
else if (mask == 1){
alert("player ok");
}
现在,我需要在接下来的电话中使用这个cookie,我知道Guzzle可以为我保存cookie,并使用" CookieJar"在下次通话中自动发送(或不发送)。或者" SessionCookieJar",我试图使用它,但是我没有在' jar中看到cookie,这就是我所做的:
$client = new Client(array(
'cookies' => true
));
$response = $client->request('POST', 'http://myapi.com/login', [
'timeout' => 30,
'form_params' => [
'email' => $request->get('email'),
'password' => $request->get('password'),
]
]);
但是,当我从POST中获取cookie时,我只能通过使用:
来查看它$newCookies = $response->getHeader('set-cookie');
并且它不在cookieJar中,因此它不会在下一次调用中发送它。 我在这里错过了什么?
谢谢!
答案 0 :(得分:8)
根据文档here,['cookies' => true]
表示对所有请求使用共享Cookie jar,而['cookies' => $jar]
表示使用特定 cookie jar($jar
)用于客户端的请求/响应。所以你需要使用:
$client = new Client(array(
'cookies' => true
));
$response = $client->request('POST', 'http://myapi.com/login', [
'timeout' => 30,
'form_params' => [
'email' => $request->get('email'),
'password' => $request->get('password'),
]
]);
// and using the same client
$response = $client->request('GET', 'http://myapi.com/next-url');
// or elsewhere ...
$client = new Client(array(
'cookies' => true
));
$response = $client->request('GET', 'http://myapi.com/next-url');
或
$jar = new CookieJar;
$client = new Client(array(
'cookies' => $jar
));
$response = $client->request('POST', 'http://myapi.com/login', [
'timeout' => 30,
'form_params' => [
'email' => $request->get('email'),
'password' => $request->get('password'),
]
]);
// and using the same client
$response = $client->request('GET', 'http://myapi.com/next-url');
// or elsewhere ...
$client = new Client(array(
'cookies' => $jar // the same $jar as above
));
$response = $client->request('GET', 'http://myapi.com/another-url');