0

Given the Proxy.java below:

import io.javalin.Javalin;
import org.eclipse.jetty.proxy.AsyncProxyServlet;
import org.eclipse.jetty.servlet.ServletHolder;

public class Proxy {
    public static void main(String[] args) {
        Javalin app = Javalin.create(config -> {
            config.jetty.contextHandlerConfig(sch -> {
                ServletHolder proxyServlet = new ServletHolder(AsyncProxyServlet.Transparent.class);
                proxyServlet.setInitParameter("proxyTo", proxyTo);
                proxyServlet.setInitParameter("prefix", "/proxy");
                sch.addServlet(proxyServlet, "/proxy/*");
                sch.addFilter(ProxyFilter.class, "/proxy/*", EnumSet.of(DispatcherType.REQUEST));
            });
        });

        app.start(5555)
    }
}

And the ProxyFilter.java looks like this:

package com.fedshop.proxy;

import java.io.IOException;

import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class ProxyFilter extends RequestContextFilter{

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
            throws ServletException, IOException {        
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request, 0);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

        try {
            super.doFilterInternal(requestWrapper, responseWrapper, filterChain);
        } finally {
                        
            byte[] responseArray = responseWrapper.getContentAsByteArray();
            Info.DATA_TRANSFER.addAndGet(responseArray.length); # length 0

            String responseStr = new String(responseArray, responseWrapper.getCharacterEncoding());
            System.out.println(responseStr); # empty

            // It is important to copy cached reponse body back to response stream to see response
            responseWrapper.copyBodyToResponse();
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

}

The problem here is that the response is empty. My hypothesis is that the response is somehow consumed, i.e, sent to the client. Given that I already cached the response. How comes the content is empty?

0 Answers0