Save packets by writing header+body as one packet where feasible.

We were previously writing the HTTP header as one byte array and
then the HTTP body as a series of byte arrays, even if the body
was quite small. With this change we prefer to write header plus
body as a single write. The downside of this approach is that in
the worst case we need to allocate 32K more bytes.

In the best case we save a packet. On my test this saved 40ms for
the roundtrip.

Is this the right approach? Allocating a right-sized buffer saves
memory and minimizes the number of packets sent. But it does make
this complex code more complex.

        benchmark postBodySize    run   ms linear runtime
HttpURLConnection         none Before 10.8 ======
HttpURLConnection         none  After 11.0 ======
HttpURLConnection            0 Before 10.9 ======
HttpURLConnection            0  After 11.1 ======
HttpURLConnection            1 Before 51.3 =============================
HttpURLConnection            1  After 11.0 ======
HttpURLConnection         1024 Before 51.7 ==============================
HttpURLConnection         1024  After 11.3 ======
HttpURLConnection         8192 Before 51.2 =============================
HttpURLConnection         8192  After 12.8 =======

http://b/3143475

Change-Id: Id22a8449118a4b8dd13e71915700ac78803d2d9f
2 files changed