How rewrite target URL in reverse proxy developed with Apache http-core-4.3.3

665 views Asked by At

I am developing a reverse proxy using http-core-4.3.3, and I need to rewrite the url, for example

/srv001/curstomer/id has to be rewrite to /curstomer/id

My development is based on this example https://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalReverseProxy.java

This is my proxy handler

public void handle(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {

    long start = System.currentTimeMillis();

    DefaultBHttpClientConnection outconn = (DefaultBHttpClientConnection) context.getAttribute(ProxyContext.HTTP_OUT_CONN);

    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, outconn);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);

    System.out.println(">> Request URI: " + request.getRequestLine().getUri());

    // Remove hop-by-hop headers
    ...

    this.httpexecutor.preProcess(request, this.httpproc, context);
    final HttpResponse targetResponse = this.httpexecutor.execute(request, outconn, context);
    this.httpexecutor.postProcess(response, this.httpproc, context);

    // Remove hop-by-hop headers
    ...

    response.setStatusLine(targetResponse.getStatusLine());
    response.setHeaders(targetResponse.getAllHeaders());
    response.setEntity(targetResponse.getEntity());

    System.out.println("<< Response: " + response.getStatusLine());

    final boolean keepalive = this.connStrategy.keepAlive(response, context);
    context.setAttribute(ProxyContext.HTTP_CONN_KEEPALIVE, new Boolean(keepalive));

    long end = System.currentTimeMillis();
    System.out.println("-- request took (msec): " + Long.toString(end - start));
}

I've tried to rewrite the target url at request, but there is no set method for doing that. How can I rewrite the target URL ?

1

There are 1 answers

0
ok2c On BEST ANSWER

HttpRequest and HttpResponse objects are very cheap. When implementing a proxy with HttpCore you should always be making a copy of incoming messages instead of passing the same object for several reasons:

  • URI rewriting being one
  • handling of so called hop-by-hop headers being another
  • protocol upgrade / downgrade when for instance a client supports HTTP/1.0 and an origin supports HTTP/1.1 or vise versa.