laravel - 使用 Laravel 和 Guzzle 检索 API 响应
问题描述
我想从我的 Laravel 项目中的 API 中得到答案。显然 Guzzle 似乎是最好的解决方案。这是版本 1.6.0b6 中的 Check_MK API
我创建了一个模型来与 API 通信以尊重 MVC 模型
模型
<?php
namespace App;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
class Hostgroup
{
public static function all() {
$client = new \GuzzleHttp\Client();
$request = new Request('GET', 'https://my-api-uri.tld', [
'query' => [
'action' => 'get_all_host',
'_username' => 'user',
'_secret' => 'secret',
'output_format' => 'json'
]]);
$hostgroup = $client->send($request, ['timeout' => 2]);
return $hostgroup;
}
}
控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Hostgroup;
class MainDashboardController extends Controller
{
public function index() {
$hostgroup = Hostgroup::all();
return view('dashboard.main', [
'hostgroup' => $hostgroup
]);
}
}
目前,我在项目页面上收到错误 500,但 API 向我发送了带有请求标头的代码 200。
其实我得到了这个:
Response {#209 ▼
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:9 [▶]
-headerNames: array:9 [▶]
-protocol: "1.1"
-stream: Stream {#207 ▼
-stream: stream resource @278 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
解决方案
$hostgroup
是Psr\Http\Message\ResponseInterface
你可能不想要的。您将需要响应的实际内容。尝试添加这个:
return $hostgroup->getBody()->getContents();
推荐阅读
- javascript - 无法访问 handleEvent 函数中的更新状态 | 反应钩子
- r - 基于(变化的)虚拟变量对 ggplot 的部分进行着色
- maven -
在 Maven 设置 xml 中 - python - 如何并行运行多个 DataFrame.to_csv()?(多线程)
- python - Python如何更改数据框格式
- memory - 将字符串放在闪存上的固定内存地址中
- javascript - JavaScript 不会保存所有的 cookie 数据
- constraints - Papyrus - 验证属性的 OCL 约束
- mysql - 在 Talend 中将所有 MYSQL 组件转换为 Greenplum 组件
- android - Zebra Datawedge 6.2.24 启用/禁用在 Zebra TC75 上不起作用