【问题标题】:Calling an API in Symfony 2 returns me html and not json在 Symfony 2 中调用 API 会返回 html 而不是 json
【发布时间】:2017-07-10 08:29:23
【问题描述】:

我提前感谢您抽出时间阅读我面临的问题。 从浏览器执行 Rest Full API (https://dusupay.com/transactions/check_status/1386/19892016.json) 从 json 返回给我。

现在我需要在控制器中检索此 API 返回的数据,但不幸的是,它返回了我之前的“文本/HTML”

use Zeroem\CurlBundle\HttpKernel\RemoteHttpKernel           
$request = Request::create("https://dusupay.com/transactions/check_status/1386/19892016.json");
$remoteKernel = new RemoteHttpKernel();
$response1 = $remoteKernel->handle($request);
return new response ($response1);

当我尝试更改 JSON 中的内容类型时,我没有收到更多答案。

感谢您的时间

【问题讨论】:

    标签: php symfony symfony-2.8


    【解决方案1】:

    使用 JsonResponse 代替 Response:

    use Symfony\Component\HttpFoundation\JsonResponse;
    

    【讨论】:

    • 看起来dusupay.com的后端是用CakePHP写的,不是@FOKOTHierry维护的
    • @jkucharovic 他从 dusupay.com 获取 json(检查他给定的 url),然后将其作为控制器内的 Response 对象返回,然后他的应用程序中没有 json,如果他愿意的话使用 JsonResponse 他将拥有 json 对象而不是简单的响应对象。
    • @Elmsas 哦……我的错——我误解了他的问题。
    【解决方案2】:

    您可以通过 Symfony 格式侦听器控制 API 的所有响应格式。 看看这个:https://symfony.com/doc/current/bundles/FOSRestBundle/3-listener-support.html

    或者对于某些特定的路线使用简单:

    return new JsonResponse($response);
    

    【讨论】:

      【解决方案3】:

      经过一些修改,问题解决了

              use Zeroem\CurlBundle\HttpKernel\RemoteHttpKernel;
          $request = Request::create("https://dusupay.com/transactions/check_status/1386/19892016.json");
      
          $remoteKernel = new RemoteHttpKernel();
          $response1 = $remoteKernel->handle($request);
          $data = json_decode($response1->getContent());
          return   new response($data->Response->customer_email);
      

      【讨论】:

        猜你喜欢
        • 2022-01-04
        • 1970-01-01
        • 2017-03-28
        • 2019-03-31
        • 2020-08-12
        • 1970-01-01
        • 2015-10-10
        • 2022-01-01
        • 1970-01-01
        相关资源
        最近更新 更多