Chunked Transfer Encoding with HttpURLConnection


Not gonna work

public void chunkLikeChuckNorris(final HttpURLConnection connection,
                                 final InputStream input) {

    connection.setRequestProperty("Transfer-Encoding", "chunked");

    assert "chunked".equals(connection.getRequestProperty("Transfer-Encoding")); // @@?

    final OutputStream output = connection.getOutputStream();

    final byte[] buffer = new byte[8192];
    for (int read = -1; (read = input.read(buffer)) != -1; ) {
        if (read == 0) {
            continue;
        }
        output.write(Integer.toHexString(read).getBytes("US-ASCII"));
        output.write('\r');
        output.write('\n');
        output.write(buffer, 0, read);
        output.write('\r');
        output.write('\n');
    }
    output.write('0');
    output.write('\r');
    output.write('\n');
}

We should do like this

public void chunkLikeRealChuckNorris(final HttpURLConnection connection,
                                     final InputStream input) {

    connection.setChunkedStreamingMode(-1);

    final OutputStream output = connection.getOutputStream();

    final byte[] buffer = new byte[8192];
    for (int read = -1; (read = input.read(buffer)) != -1; ) {
        output.write(buffer, 0, read); // just a plain stream copy
    }
}

What about pre 1.5?

The HttpURLConnection.html#setChunkedStreamingMode(int) is since 1.5. I wonder how we used to do that.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s