guzzlehttp和symfony与其余api问题

时间:2018-11-14 09:58:38

标签: symfony guzzle

我想使用guzzlehttp中的symfony使用rest api进行发布调用...
我写了这段代码,但响应

/**
 * @Route("/post/")
 */
public function postAction()
{
    $client = new \GuzzleHttp\Client();
    $response = $client->request('POST', $url, [
        'form_params' => [
            'username' => 'test',
            'password' => 'test',
        ]
    ]);

    return $this->render('esterne/post.html.twig', array(
        'response'=>$response,
    ));
}

这是树枝文件 post.html.twig

{{response}}

结果是这样

{"status":"200","data":{"is_auth":true,"userToken":"194b873c004716acb3e0a5fba09fe405"}}

但是如果我输入html:

return $this->render('esterne/post.html.twig', array(
    'response'=>$response->getBody(),
));

它导致错误500内部服务器错误

  

[2018-11-14 09:56:35] request.CRITICAL:未捕获的PHP异常Twig_Error_Runtime:“在呈现模板期间引发了异常(“可捕获的致命错误:GuzzleHttp \ Psr7 \ Response类的对象无法转换为字符串“)。”在/app/app/Resources/views/esterne/post.html.twig第1行{“ exception”:“ [object](Twig_Error_Runtime(code:0):在呈现模板期间引发了异常(\”可捕获的致命错误:无法将类GuzzleHttp \ Psr7 \ Response的对象转换为字符串\“)。在/app/app/Resources/views/esterne/post.html.twig:1,ErrorException(code:0):可捕获致命错误:无法在/app/var/cache/prod/twig/47/478ca9f9b0a5c69caa7b0fed874bf831466230764635f396f057dc2c33868549.php:23)将GuzzleHttp \ Psr7 \ Response类的对象转换为字符串

解决方案

使用文件

{{ response|json_encode()|raw }}

在树枝和

return $this->render('esterne/post.html.twig', array(
    'response'=>json_decode($response->getBody()->getContents(), FALSE),
));

1 个答案:

答案 0 :(得分:0)

您可以尝试以下回复。

return $this->render('esterne/post.html.twig', array(
    'response'=>$response->getBody()->getContent(),
));
相关问题