Guzzle Laravel - 使用POST请求登录

时间:2017-07-02 21:17:49

标签: php json laravel

我要做的是登录外部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'数组,但没有工作。

基本上,我无法做的是使用Guzzle登录API。

1 个答案:

答案 0 :(得分:1)

这是一个应该有效的基本流程

// 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);
相关问题