首页 > 解决方案 > guzzlehttp 和 symfony 与 rest api 问题

问题描述

我想使用guzzlehttpin使用 rest api 进行 post callsymfony
写了这段代码,但响应

/**
 * @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(代码:0):可捕获致命错误:GuzzleHttp\Psr7\Response 类的对象无法在 /app/var/cache/prod/twig/47/478ca9f9b0a5c69caa7b0fed874bf831466230764635f396f057dc2c33868549.php:23 处转换为字符串”

解决方案

使用文件

{{ response|json_encode()|raw }}

在树枝和

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

标签: symfonyguzzle

解决方案


您可以尝试以下回复。

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

推荐阅读