【问题标题】:guzzlehttp and symfony with rest api problemguzzlehttp 和 symfony 与 rest api 问题
【发布时间】:2018-11-15 20:51:03
【问题描述】:

我想在symfony 中使用guzzlehttp 使用rest api 进行post call ...
我写了这段代码,但是响应

/**
 * @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),
));

【问题讨论】:

标签: symfony guzzle


【解决方案1】:

您可以尝试以下回复。

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

【讨论】:

  • 错误...不起作用 2018-11-14T10:20:40.804640+00:00 app[web.1]: [2018-11-14 10:20:40] php.CRITICAL:调用未定义的方法 GuzzleHttp\Psr7\Stream::getContent() {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): 调用未定义的方法 GuzzleHttp\\ Psr7\\Stream::getContent() at /app/src/AppBundle/Controller/EsterneController.php:109)"} []
  • ->getContents() 应该被使用而不是->getContent()
  • 现在没有错误....但是结果不在json中...查看页面的来源是html {“status”:“200”,“data”:{“ ;is_auth":true,"userToken":"9a1d168594a9755d849abe283b3505ea"}}
  • 你应该被用来代替上面的。 json_decode($response->getBody(), true);或 json_decode($response->getBody()->getContents(), true)
  • ok ... 在这两种情况下结果都是 json 但在响应中出现 Array ... 为什么?
猜你喜欢
  • 2022-01-23
  • 2015-10-08
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 2020-11-30
相关资源
最近更新 更多