- All Implemented Interfaces:
- Closeable, AutoCloseable, org.apache.http.HttpEntity, org.apache.http.nio.entity.HttpAsyncContentProducer, DigestSelfSigningCapable
public final class GsonHttpEntity
extends Object
implements org.apache.http.HttpEntity, org.apache.http.nio.entity.HttpAsyncContentProducer, DigestSelfSigningCapable
Optimised adapter to encode GSON objects into HttpEntity instances.
The naive approach was using various StringBuilders; the objects we
need to serialise into JSON might get large and this was causing the
internal StringBuilder buffers to need frequent resizing and cause
problems with excessive allocations.
Rather than trying to guess reasonable default sizes for these buffers,
we can defer the serialisation to write directly into the ByteBuffer
of the HTTP client, this has the additional benefit of making the
intermediary buffers short lived.
The one complexity to watch for is flow control: when writing into
the output buffer chances are that not all bytes are accepted; in
this case we have to hold on the remaining portion of data to
be written when the flow control is re-enabled.
A side effect of this strategy is that the total content length which
is being produced is not known in advance. Not reporting the length
in advance to the Apache Http client causes it to use chunked-encoding,
which is great for large blocks but not optimal for small messages.
For this reason we attempt to start encoding into a small buffer
upfront: if all data we need to produce fits into that then we can
report the content length; if not the encoding completion will be deferred
but not resetting so to avoid repeating encoding work.
- Author:
- Sanne Grinovero (C) 2017 Red Hat Inc.