2016-09-20 10 views
0
罰款

我試圖訪問下列公共API資源:當我試圖在瀏覽器中400在狂飲API端點的錯誤是工作在瀏覽器與郵差

http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003

,它下載一個JSON文件。當我在郵遞員試用它時,它顯示爲文本(JSON格式)。

當我在Guzzle中嘗試時,出現400錯誤。

$apiResource = "http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003"; 

try { 
    $client = new Client(); 
    $res = $client->request('GET', $apiResource); 
} 
catch (\GuzzleHttp\Exception\BadResponseException $e) { 
    die($e->getMessage()); 
} 

我懷疑問題是什麼做的API返回

Content-Disposition attachment 

在標題中,但我不知道什麼狂飲來處理這個正確的方式是。

只是要清楚,我想獲取原始文本輸出,而不是作爲附件的文件。

回答

2

所有你需要做的是get the body of the response(其放入Stream對象),然後獲取響應的內容:

try { 
    $client = new Client(); 
    $res = $client->request('GET', $apiResource)->getBody()->getContents(); 
} 
catch (\GuzzleHttp\Exception\BadResponseException $e) { 
    die($e->getMessage()); 
} 

編輯

$apiResource = "http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003"; 

確切的代碼使用測試:

Route::get('/guzzletest', function() { 
    $apiResource = "http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003"; 

    try { 
     // use GuzzleHttp\Client; 
     $client = new Client(); 
     $res = $client->request('GET', $apiResource)->getBody()->getContents(); 
     dd($res); 
    } 
    catch (\GuzzleHttp\Exception\BadResponseException $e) { 
     die($e->getMessage()); 
    } 
}); 
+0

謝謝,但仍然是400恐怕。 –

+0

你確定這是你所有的代碼嗎?我測試了該代碼並收到了json主體。我將用我的確切代碼編輯我的文章。 – Samsquanch

+0

我的錯誤,你的方式確實有效。非常感謝。 –