1

I have a Controller that must forward the received request (changing some query parameters) to another server, and returns it's response (with same headers, status and body).

I decided to use HttpClient for doing that.

The problem is that HttpClient converts the content (i.e.: deflating gzip requests), and it breaks the output response.

Here is part of the example:

        $response = $client->request($request->getMethod(), $extUrl, [
            'headers' => $reqHeaders,
            'timeout' => 45,
            'verify_host' => false,
            'verify_peer' => false,
            'body' => $request->getContent(),
        ]);

        #response data
        $body = $response->getContent(false);
        $statusCode = $response->getStatusCode();
        $headers = $response->getHeaders(false);

        return new Response($body, $statusCode, $headers);

Considering the second server returns a gzipped content, the response is broken, because it would keep the response header (content-type) but the $body will not be exactly the same, because HttpClient do me the favor of deflate the content.

The question is: is there a way to tell HttpClient to do not touch in my response body?

Or: is there a better way to make this "proxy" controller action?

1 Answer 1

1

I found that if accept-encoding is defined in the request headers, it's not inflated by CurlResponse class...

    #\Symfony\Component\HttpClient\Response\ResponseTrait::$inflate
    $this->inflate = !isset($options['normalized_headers']['accept-encoding']);

And

    #\Symfony\Component\HttpClient\Response\response
    $response->inflate = \extension_loaded('zlib') && $response->inflate && 'gzip' === ($response->headers['content-encoding'][0] ?? null) ? inflate_init(ZLIB_ENCODING_GZIP) : null;

So, I specified some empty encoding for those cases.

    if (empty($request->headers->get('accept-encoding'))) {
        //adding some accept-encoding will make httpclient response not to deflate the response (gzdecode) automatically
        $request->headers->add(['accept-encoding'=> '']);
    }

I still don't know if this is the best approach to forward a request and it's response in the controller, but the above solution solved my problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.