2017-07-02 183 views
0

我想要做的是登錄到外部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

回答

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