如何使用嵌入式jetty模拟代理服务器?

时间:2013-11-12 00:21:03

标签: java servlets proxy jetty embedded-jetty

我有i个代理,每个代理都有不同的IP host_i

我想向

发出请求

<host_i>:4444/content转到

localhost:9999/content?proxy=<host_i>

我该怎么做?这是我到目前为止尝试使用嵌入式jetty服务器(版本:8.1.10.v20130312),但它不起作用,我无法弄清楚这一点。我从http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/AsyncProxyServer.java?h=jetty-8

得到了这个例子
    proxyServer = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(4444);
    proxyServer.setConnectors(new Connector[]{connector});

    ServletHandler handler = new ServletHandler();
    proxyServer.setHandler(handler);

    ServletHolder proxy = handler.addServletWithMapping("org.eclipse.jetty.servlets.ProxyServlet", "/");
    proxy.setAsyncSupported(true);

    proxyServer.start();

这是我使用simpleframework来处理localhost:9999的请求的代码:

    websiteContainer = new HttpServer();
    websiteServer = new ContainerServer(websiteContainer);
    websiteConnection = new SocketConnection(websiteServer);
    final SocketAddress websiteAddress = new InetSocketAddress(9999);
    websiteConnection.connect(websiteAddress);

    public class HttpServer implements Container {
    @Override
    public void handle(final Request request, final Response response) {
            // do some stuff here, I have a breakpoint here to test if a request to a proxy made it here
    }

1 个答案:

答案 0 :(得分:0)

@Override
public void handle(final Request request, final Response response) {
// building redirect url localhost:9999/content?proxy=<host_i>

 redirectUrl= "localhost:9999/" + httpRequest.getContextPath() + "? proxy =" + httpRequest.getLocalAddr();            
// do remaing stuff here
}

我希望这可以解决您的问题,因为httpRequest.getContextPath()会为您提供应用运行位置的IP,而httpRequest.getContextPath()会为您提供传感器路径