'In Gateway Zuul Filters, how to modify the ContentType of an API request

My requirement is to receive an encrypted request of content-type text/plain. Using the zuul pre filter I will have to decrypt the request and forward the decrypted request to the underlying services.

But all the services are expecting a request of content-type application/json. Because of which it is returning a 415 error.

I had tried modifying the content type using the below method, but still its giving a 415 error.

public void modifyRequestBody(String requestBody, RequestContext context) {
         .....
        //code to decrypt request body
         .....

        HttpServletRequest request = context.getRequest();
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
        mutableRequest.putHeader("Content-Type", APPLICATION_JSON_WITH_UTF8_CHARSET);

        byte[] bytes = StringUtils.isBlank(plainText) ? requestBody.getBytes(StandardCharsets.UTF_8)
                : plainText.getBytes(StandardCharsets.UTF_8);
        context.setRequest(new HttpServletRequestWrapper(mutableRequest) {
            @Override
            public ServletInputStream getInputStream() throws IOException {
                return new ServletInputStreamWrapper(bytes);
            }

            @Override
            public int getContentLength() {
                return bytes.length;
            }

            @Override
            public long getContentLengthLong() {
                return bytes.length;
            }

            @Override
            public String getContentType() {
                return APPLICATION_JSON_WITH_UTF8_CHARSET;
            }

        });
    }

The MuttableHttpServletRequest class was implemented based on the approach mentioned here : link

Not sure if something else needs to be changed. Any help would be appreciated.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source