Usage of consumeContent() of HttpEntity

夙愿已清 提交于 2019-12-02 09:23:31

问题


What is the purpose of consumeContent() of class or org.apache.http.HttpEntity in Android?

When should one use it ane can it have side effects?

I'm trying to fix a bug in an app which makes requests to a server using HttpClient and sometimes if one particular request fails it will subsequently fail despite the fact that internet is OK. The app calls this method at the end of input stream read.


回答1:


As @Sotirios suggested, HttpEntity.consumeContent() is deprecated so please use EntityUtils.consume(HttpEntity) when feasible.

Let's then broadly talk about consuming an HttpEntity. Consuming an HttpEntity ensures that all the resources allocated to this entity are deallocated. This means that:

  • The underlying stream is released.
  • If your connection is pooled, your connection object will be given back to the pool. If your connection is not pooled, the connection manager will let go the connection object in question and focus on handling other client requests.

When should one use it?

You should free connection resources the moment they are no longer needed. Consuming an HttpEntity does exactly this for you.

Can it have side effects?

I am unaware of any side effects of consuming an HttpEntity.




回答2:


As you can see in the javadoc, that method is deprecated. Don't use it. It's implementation-dependent. But it should be implemented as described:

This method is called to indicate that the content of this entity is no longer required. All entity implementations are expected to release all allocated resources as a result of this method invocation

Instead, you should be using EntityUtils.consume(HttpEntity) which is implemented as such

public static void consume(final HttpEntity entity) throws IOException {
    if (entity == null) {
        return;
    }
    if (entity.isStreaming()) {
        final InputStream instream = entity.getContent();
        if (instream != null) {
            instream.close();
        }
    }
} 

It's simply closing the underlying InputStream if necessary.



来源:https://stackoverflow.com/questions/21818169/usage-of-consumecontent-of-httpentity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!