Guzzle Laravel - 使用POST请求登录

问题描述:

我想要做的是登录到外部API并检索JSON文件。为此,我在Laravel使用Guzzle。Guzzle Laravel - 使用POST请求登录

我有安装一个控制器来做到这一点:

$client = new Client([ 
     'base_uri' => 'https://www.space-track.org', 
     'timeout' => 2.0, 
    ]); 

我访问使用JSON文件:

$response = $client->request('GET', '/basicspacedata/query/class/boxscore'); 

为了得到我需要登录到API的JSON文件。 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。

+0

线的东西为什么不只是后登录参数,如'$客户 - >后('https://www.space-track.org/ ajaxauth/login?identity = your_username&password = your_password')',然后获取令牌或类似的东西。 – hasandz

这是一个基本的流程,应该工作现在

// 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);