javafilterproxylittle-proxy

Create a reverse proxy by littleproxy


I'm a beginner with littleproxy, how can I create a reverse proxy server?

My proxy get requests from clients and sends them to servers (servers only a regular site same as www.xxx.com contain only web page(in not rest) and proxy get response from server(a web page) and return to client.

For example, client url is localhost:8080/x, proxy maps it to www.myserver.com/xy and shows xy page for client. How can do it by using a filter or a httpservlet.

My http servlet will be as follow:

 public class ProxyFilter implements Filter {
      public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        HttpProxyServer server =
        DefaultHttpProxyServer.bootstrap()
        .withPort(8080)
        .withFiltersSource(new HttpFiltersSourceAdapter() {
            public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) {
               return new HttpFiltersAdapter(originalRequest) {
                  @Override
                  public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return null;
                  }

                  @Override
                  public HttpResponse proxyToServerRequest(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return null;
                  }

                  @Override
                  public HttpObject serverToProxyResponse(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return httpObject;
                  }

                  @Override
                  public HttpObject proxyToClientResponse(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return httpObject;
                  }   
               };
            }
        })
        .start();
    }
    public void init(FilterConfig config) throws ServletException {

    }
    public void destroy() {

    }
}

Solution

  • LittleProxy uses Host header to do the routing. So simplest thing you can do is set Host as the real server in clientToProxyRequest method.

    
        public HttpResponse clientToProxyRequest(HttpObject httpObject) {
            if(httpObject instanceof FullHttpRequest) {
                FullHttpRequest httpRequest = (FullHttpRequest)httpObject;
                httpRequest.headers().remove("Host");
                httpRequest.headers().add("Host", "myserver.com:8080");
            }
            return null;
        }