如何在 Guzzle 通话中跳过登录屏幕
题
我必须使用 cURL 将信息发送到外部网站。我在 Laravel 应用程序上设置了 Guzzle。我已经设置了基础知识,但根据网站的文档,需要执行用户名和密码操作。如何传递“操作”以及登录和访问所需的凭据?
该网站指出:
curl [-k] –dump-header <header_file> -F “action=login” -F “username=<username>” -F “password=<password>” https://<website_URL>
我的控制器:
$client = new \GuzzleHttp\Client();
$response = $client->get('http://website.com/page/login/', array(
'auth' => array('username', 'password')
));
$xml = $response;
echo $xml;
该网站将加载到 echo
, ,但它只会拉起登录屏幕。我需要这些凭据来绕过登录屏幕(登录成功)以获取 cURL 所需的部分信息。
解决方案
curl -F
提交 POST 请求而不是 GET 请求。所以你需要相应地修改你的代码,比如
$client = new \GuzzleHttp\Client();
$response = $client->post('http://website.com/page/login/', [
'body' => [
'username' => $username,
'password' => $password,
'action' => 'login'
],
'cookies' => true
]
);
$xml = $response;
echo $xml;
看 http://guzzle.readthedocs.org/en/latest/quickstart.html#post-requests, http://curl.haxx.se/docs/manpage.html#-F
编辑:
只需添加 ['cookies' => true]
请求以使用与此关联的身份验证 cookie GuzzleHttp\Client()
. http://guzzle.readthedocs.org/en/latest/clients.html#cookies
$response2 = $client->get('http://website.com/otherpage/', ['cookies' => true]);
其他提示
我无法让 @JeremiahWinsley 的答案在较新版本的 Guzzle 上工作,因此我更新了他们的代码以从 Guzzle 5.x 开始工作。
需要三项重大改变
- 使用
form_params
代替body
防止出现错误“已弃用将“body”请求选项作为数组传递以发送 POST 请求。” - 更改 cookie 以使用
CookieJar
目的 - 使用
->getBody()->getContents()
得到 请求正文
这是更新后的代码:
$client = new \GuzzleHttp\Client();
$cookieJar = new \GuzzleHttp\Cookie\CookieJar();
$response = $client->post('http://website.com/page/login/', [
'form_params' => [
'username' => $username,
'password' => $password,
'action' => 'login'
],
'cookies' => $cookieJar
]
);
$xml = $response->getBody()->getContents();
echo $xml;
要在将来的请求中继续使用 cookie,请传入 cookieJar
根据请求:
$response2 = $client->get('http://website.com/otherpage/', ['cookies' => $cookieJar]);
我无法让 @JeremiahWinsley 和 @Samsquanch 的答案在新版本的 Guzzle 上工作。因此,我更新了代码,以便从 Guzzle 6.x 开始工作。
狂饮 6.x。文件: http://docs.guzzlephp.org/en/stable/index.html
这是更新后的代码:
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
try {
$client = new Client();
$cookieJar = new CookieJar();
$response = $client->request('POST', 'http://website.com/page/login/', [
'form_params' => [
'username' => 'test@example.com',
'password' => '123456'
],
'cookies' => $cookieJar
]);
$response2 = $client->request('GET', 'http://website.com/otherpage/', [
'cookies' => $cookieJar
]);
if ($response2->getStatusCode() == 200) {
return $response2->getBody()->getContents();
} else {
return "Oops!";
}
} catch (\Exception $exception) {
return 'Caught exception: ', $exception->getMessage();
}