首页 > 解决方案 > HTTP Guzzle 未返回所有数据

问题描述

我创建了一个使用 Guzzle 联系远程 API 的函数,但我无法让它返回所有可用数据。

我在这里调用函数:

$arr = array(
    'skip' => 0,
    'take' => 1000,
);
$sims = api_request('sims', $arr);

这是函数,我在$response变量中尝试了以下内容

json_decode($x->getBody(), true)

json_decode($x->getBody()->getContents(), true)

但两者都没有显示更多记录。它返回 10 条记录,我知道它应该返回超过 51 条记录。

use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
    $username = '***';
    $password = '***';
    
    //use GuzzleHttp\Client;
    $client = new Client([
        'auth' => [$username, $password],
    ]);
    
    $auth_header = 'Basic '.$username.':'.$password;
    $headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
    $json_data = json_encode($vars);
    $end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
    
    try {
        $x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
        $response = array(
            'success' => true,
            'response' => // SEE ABOVE //
        );
    } catch (GuzzleHttp\Exception\ClientException $e) {
        $response = array(
            'success' => false,
            'errors' => json_decode($e->getResponse()->getBody(true)),
        );
    }
    
    return $response;
}

标签: phpguzzle

解决方案


通过阅读https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take上的文档,我假设服务器不接受该 GET 请求正文中的参数并假设默认值为10、由于在很多应用中很正常,get请求往往只使用查询字符串参数。

在该函数中,我会尝试更改它以在 POST/PUT/PATCH 请求的情况下发送正文,在 GET/DELETE 请求的情况下发送不带 json_encode 的“查询”。来自 guzzle 文档的示例:

$client->request('GET', 'http://httpbin.org', [
    'query' => ['foo' => 'bar']
]);

来源:https ://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters


推荐阅读