drmg17928 2016-11-20 20:21
浏览 42

如何将卷曲外部原始响应转发到SF Response对象?

I need to make a route in a Symfony 3 app (server 1), which has to send a (filtered) request on a server 2, then send back the exact response given by the server 2 (same HTTP status code, headers and body).

With the native curl Php library, you can get the raw response (including headers), by setting the CURLOPT_HEADER option to True.

But the Response object from Symfony HttpFoundation seems to be only configurable by setting separately headers (inside the constructor, or with $response->headers->set()) and body (with $response->setContent(). I didn't find a way to set a raw response (with headers) into the Response object.

Is it possible, or how could it be done otherwise?

Here's my try:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MyController extends Controller
{
    /**
     * @Route("/get", name="get")
     */
    public function getAction(Request $request)
    {
        // Filter/modify the query string, but keep it quite similar:
        $request->query->remove('some_private_attr');
        $my_query_string = http_build_query($request->query->all());

        // Setup the curl request:
        $curl = curl_init('http://localhost?'.$my_query_string);
        curl_setopt($curl, CURLOPT_HEADER, 1); // Include headers
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // Return data as a string
        curl_setopt($curl, CURLOPT_PORT, 8200);

        // Perform the request, returning the raw response
        // (headers included) as a string:
        $result = curl_exec($curl);

        // Get the response status code:
        $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_close($curl);

        // Here, how can I pass the raw external response ($result)
        // to a new Response object, without parsing the header
        // and body parts unnecessarily?

        // Of course, the following doesn't send the right headers:
        $response = new Response($result, $status_code);

        return $response;
    }
}
  • 写回答

1条回答 默认 最新

  • doudou5421 2016-11-21 03:48
    关注

    You should be able to use (for example):

    $response->headers->set('Content-Type', 'text/plain');
    

    which is described here: http://symfony.com/doc/current/components/http_foundation.html#response

    The Response API also describes each of the methods. I'm not certain what type of header you need to send.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据