【问题标题】:API response returns JSON without Response BodyAPI 响应返回没有响应正文的 JSON
【发布时间】:2019-10-28 08:28:14
【问题描述】:

使用 Guzzle,我正在使用一些 JSON 格式的外部 API, 通常我会用

$data = $request->getBody()->getContents();

但我无法从这个不同的 api 获取数据。 数据似乎没有出现在“响应正文”中。

此 api 调用有效: https://i.ibb.co/80Yk6dx/Screenshot-2.png

这不起作用: https://i.ibb.co/C239ghy/Screenshot-3.png

public function getRemoteCienciaVitaeDistinctions()
{
    $client = new Client(['headers' => ['Accept' => 'application/json']]);

    $request = $client->get(
        'https://................/',
        [
            'auth'          => ['...', '...'],
        ]

    );

    $data = $request->getBody()->getContents();
    return $data;
}

【问题讨论】:

  • 您的问题不完整,您使用的是什么库?是不是大吃一惊?
  • 是的,对不起,是 Guzzle。
  • 这是什么返回:$request->getBody()->getContents() 实际应该返回什么?
  • 它返回一个空字符串,它应该返回一个带有数据的json
  • 试试这个来检查你的代码是否工作https://reqres.in/api/products/3这是返回示例json代码。删除您的身份验证

标签: php json laravel request guzzle


【解决方案1】:

第二次调用正常,但响应为空, 正如我们在 Screenshot-3 中看到的那样,Total = 0,所以这个 API 的响应是空的。

为了正确处理,我建议您对您的方法进行此修改:

public function getRemoteCienciaVitaeDistinctions()
{
    $client = new Client(['headers' => ['Accept' => 'application/json']]);

    $request = $client->get(
        'https://................/',
        [
            'auth'          => ['...', '...'],
        ]

    );

    //Notice that i have decoded the response from json objects to php array here.

    $response = json_decode($request->getBody()->getContents());

    if(isset($response->total) && $response->total == 0) return [];

    return $response;
}

请查看您正在使用的 API 的文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2017-09-23
    • 1970-01-01
    • 2020-02-15
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多