简体   繁体   English

如何两次使用HttpEntity?

[英]How to consume HttpEntity twice?

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); 如果我使用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. 该页面未提供给客户端,因为HttpEntity已被使用。

Any idea on how to solve this? 关于如何解决这个问题的任何想法?

  • A streamed, non-repeatable entity that obtains its content from 流式,不可重复的实体,可从中获取其内容
    • an {@link InputStream}. {@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. 如果是这样,我认为您可以再次为缓存调用“ getEntity()”。

HTTP entities backed by a stream from an open connection are inherently non-repeatable and therefore cannot be consumed more than once. 来自开放连接的流支持的HTTP实体本质上是不可重复的,因此不能被多次使用。 Your only option is to make the entity repeatable by buffering its content in memory or in a file. 您唯一的选择是通过在内存或文件中缓冲其内容来使实体可重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM