我正在尝试访问以下公共API资源:
当我在浏览器中尝试它时,它会作为JSON文件下载。当我在Postman中尝试它时,它显示为文本(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
在标题中,但我不知道Guzzle处理这个问题的正确方法是什么。
为了清楚起见,我想获取原始文本输出而不是文件作为附件。
答案 0 :(得分:2)
您需要做的只是get the body of the response(放入Stream对象),然后获取该响应的内容:
$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)->getBody()->getContents();
}
catch (\GuzzleHttp\Exception\BadResponseException $e) {
die($e->getMessage());
}
编辑:
用于测试的确切代码:
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());
}
});