php - 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;
}
解决方案
通过阅读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
推荐阅读
- firebase - 在集合中创建随机文档时,有没有办法对集合进行排序?
- kubernetes - 对正在运行的 Kubernetes pod 进行脚本编辑
- html - 具有移动背景的 css 剪辑文本
- html - 当一张卡片获得更多内容时,w3-cards 不会调整高度
- python - 将图像转换为 TFRecords 后如何提取图像名称?
- javascript - Nodejs Scraper 没有移动到下一页
- sql - SQL 函数通过引用获取列
- javascript - 为什么我可以调用外部文件,但不能调用内部文件?
- java - XPath 返回一个元素但不返回另一个?
- javascript - 等效于使用 javascript 更改页面内容后的 readystatechange