我尝试做的是登录到外部API并检索一个JSON文件。为此,我使用了Laravel中的Guzzle。
我已经设置了一个控制器来执行此操作:
$client = new Client([
'base_uri' => 'https://www.space-track.org',
'timeout' => 2.0,
]);我使用以下命令访问JSON文件:
$response = $client->request('GET', '/basicspacedata/query/class/boxscore');为了获得JSON文件,我需要登录到API。API教程告诉我:
Login by sending a HTTP POST request ('identity=your_username&password=your_password') to: https://www.space-track.org/ajaxauth/login我不能做的是使用Guzzle登录到API。我试着学习了几个Guzzle教程,并使用了“auth”数组,但都不起作用。
基本上,我不能做的是登录到API使用Guzzle。
发布于 2017-07-03 11:16:31
下面是一个基本的工作流程
// Initialize the client
$api = new Client([
'base_uri' => 'https://www.space-track.org',
'cookies' => true, // You have to have cookies turned on for this API to work
]);
// Login
$api->post('ajaxauth/login', [
'form_params' => [
'identity' => '<username>', // use your actual username
'password' => '<password>', // use your actual password
],
]);
// Fetch
$response = $api->get('basicspacedata/query/class/boxscore/format/json');
// and decode some data
$boxscore = json_decode($response->getBody()->getContents());
// And logout
$api->get('ajaxauth/logout');
dd($boxscore);现在,如果它不是一次性请求,并且您打算广泛使用此API,则可以将这种“丑陋”封装在您自己的服务类中,该服务类公开了一个有意义的内部API,允许您编写类似于
$spaceTrack = new App\Services\SpaceTrack\Client();
$boxscore = $spaceTrack->getBoxscore();
dd($boxscore);https://stackoverflow.com/questions/44875288
复制相似问题