Question

I'm making a basic proxy, and I'm currently trying to send a response to the client AND to cache this response for future use.

I have the following function:

    public HttpResponse sendRequestToServer(HttpRequest request)
{
    int bufsize = 8 * 1024;
    HttpHost host = this.getHost(request);
    HttpResponse response = null;

    try
    {
        Socket outsocket = new Socket(host.getHostName(), host.getPort());
        DefaultBHttpClientConnection outconn = new DefaultBHttpClientConnection(bufsize);
        outconn.bind(outsocket);

        HttpProcessor httpproc = HttpProcessorBuilder.create()
        .add(new RequestContent())
        .add(new RequestTargetHost())
        .add(new RequestConnControl())
        .add(new RequestUserAgent("ProxyServer 1.0"))
        .add(new RequestExpectContinue(true)).build();

        System.out.println("Outgoing connection to : " + outsocket.getInetAddress());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpCoreContext context = HttpCoreContext.create();
        context.setTargetHost(host);

        httpexecutor.preProcess(request, httpproc, context);
        response = httpexecutor.execute(request, outconn, context);
        httpexecutor.postProcess(response, httpproc, context);
    }
    catch(IOException | HttpException e)
    {
        System.err.println("Error sending request: " + e);
    }
    return response;
}

If I use inconn.sendResponseEntity(response);, the client get the response without any trouble.

Yet if I write:

String sourceString = EntityUtils.toString(response.getEntity());

inconn.sendResponseHeader(response);
inconn.sendResponseEntity(response);

The page is not served to the client because the HttpEntity has already been consumed.

Any idea on how to solve this?

No correct solution

OTHER TIPS

  • A streamed, non-repeatable entity that obtains its content from
    • an {@link InputStream}.

Each of the entity classes state whether or not its repeatable.... as in the code comment above. Verify which entity class you use for your response and whether the entity is repeatible. If it is then i think that you can just call 'getEntity()' again for your cache.

HTTP entities backed by a stream from an open connection are inherently non-repeatable and therefore cannot be consumed more than once. Your only option is to make the entity repeatable by buffering its content in memory or in a file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top