Guzzle 中 API 端点上的 400 错误在浏览器和 Postman 中工作正常

400 Error on API endpoint in Guzzle that works fine in Browser & Postman

我正在尝试访问以下 public 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 文件。当我在 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

在header中,但我不知道Guzzle的正确处理方式是什么。

明确一点,我想要获取原始文本输出,而不是作为附件的文件。

您需要做的就是 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());
    }
});