【问题标题】:Retrieve an API response with Laravel and Guzzle使用 Laravel 和 Guzzle 检索 API 响应
【发布时间】:2019-12-27 18:11:12
【问题描述】:

我想从我的 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: []
  }
}

【问题讨论】:

    标签: laravel api guzzle


    【解决方案1】:

    $hostgroup 是您可能不想要的Psr\Http\Message\ResponseInterface。您将需要响应的实际内容。尝试添加这个:

    return $hostgroup->getBody()->getContents();
    

    【讨论】:

      【解决方案2】:

      首先,我需要你调用 Guzzle 如下: 替换:

      $request = new Request('GET', 'https://my-api-uri.tld', [
      

      与:

      $request = $client->get('https://my-api-uri.tld', [
      

      并调试来自函数 ALL 的响应 制作

      dd($hostgroup);
      

      并检查结果并比较来自 API 的内容。 也不需要使用那些:

      use GuzzleHttp\Client;
      use GuzzleHttp\Psr7\Request;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-28
        • 2023-03-10
        • 1970-01-01
        • 2019-08-04
        • 1970-01-01
        • 2019-09-08
        • 2015-07-05
        • 2020-02-07
        相关资源
        最近更新 更多