我必须使用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]
添加到请求中,以便使用与此GuzzleHttp'Client()
关联的验证cookie。http://guzzle.readthedocs.org/en/latest/clients.html饼干
$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();
}