Guzzleコールで過去のログイン画面を取得する方法
質問
CURLを使用して外部webサイトに情報を送信する必要があります。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
GET要求の代わりにPOST要求を送信します。そのため、次のようにコードを変更する必要があります
$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で動作するように@JeremiahWinsleyの答えを得るのに苦労していたので、Guzzle5の時点で動作するようにコードを更新しました。x.
三つの大きな変更が必要です
- を使用して
form_params
の代わりにbody
POSTリクエストを送信するために、「body」リクエストオプションを配列として渡す」というエラーを防ぐために、非推奨になりました。" - クッキーを使用するように変更する
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で動作させるのに苦労していました。だから私はGuzzle6のように動作するようにコードを更新しました。x.
GUZZLE6.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();
}