【问题标题】:Laravel + GuzzleHTTP no response data?Laravel + GuzzleHTTP 没有响应数据?
【发布时间】:2017-06-05 10:28:28
【问题描述】:

我正在使用 guzzle 查询我的 API。

$client = new Client();
        $response = $client->post('xxxxxx',
            array(
                'headers' => array('Content-Type'=>'application/json'),
                'json'=> array(
                    "type" => 0,
                    [...]
                )
            )
        );

        //$response = json_decode($response);

        dd($response->getBody());

这应该给我这样的输出:

{
  "returnCode": 0,
  "success": true
}

但我得到了别的东西。

Stream {#230 ▼
  -stream: stream resource @12 ▼
    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: []
}

谁能帮助我或告诉我我做错了什么?我想发送原始帖子数据并在之后获取原始帖子数据然后我想保存(例如在数据库中)。

【问题讨论】:

    标签: json laravel post guzzle


    【解决方案1】:
    getBody()
    

    返回一个流接口。您想获取该流的内容,因此:

    $response->getBody()->getContents();
    

    就是你要找的东西

    注意

    根据文档,您还可以将流接口转换为字符串,但我得到了不同的结果。 getContents() 总是做它需要做的事情,所以这是我的解决方案。

    【讨论】:

    • 这个完美,它应该如何工作。唯一让我困扰的是,它将 json 对象作为字符串返回给我。 "{"returnCode":0,"success":true}"。我可以以某种方式转换吗?
    • 如果你的意思是你希望你的 JSON 是一个字符串,它已经是。如果您想将该字符串设为 php 对象,只需执行 json_decode($response->getBody()->getContents())
    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 2021-02-05
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多