首页 文章

如何使用Apache http-core-4.3.3开发的反向代理中的重写目标URL

提问于
浏览
0

我正在使用http-core-4.3.3开发反向代理,我需要重写url,例如

/ srv001 / curstomer / id必须重写为/ curstomer / id

我的开发基于这个例子https://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalReverseProxy.java

这是我的代理处理程序

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

我曾尝试在请求时重写目标url,但没有设置方法 . 如何重写目标网址?

1 回答

  • 1

    HttpRequest和HttpResponse对象非常便宜 . 使用HttpCore实现代理时,您应始终制作传入消息的副本,而不是传递相同的对象,原因如下:

    • URI重写为一

    • 处理所谓的逐跳报头是另一种

    • 协议升级/降级,例如客户端支持HTTP / 1.0且源支持HTTP / 1.1或反之亦然 .

相关问题