由littleproxy创建反向代理

时间:2015-04-25 12:34:30

标签: java filter proxy little-proxy

我是littleproxy的初学者,如何创建反向代理服务器?

我的代理从客户端获取请求并将它们发送到服务器(服务器只有与www.xxx.com相同的常规站点仅包含网页(不休息)和代理从服务器获取响应(网页)并返回到客户。

例如,客户端网址为localhost:8080/x,代理将其映射到www.myserver.com/xy并显示客户端的xy页面。如何通过使用过滤器或httpservlet来做到这一点。

我的http servlet如下:

 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() {

    }
}

1 个答案:

答案 0 :(得分:3)

LittleProxy使用Host标头进行路由。您可以做的最简单的事情是将Host设置为clientToProxyRequest方法中的真实服务器。


    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;
    }