From 25a753691a80186cd4d7086b12c0e52225d95897 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Fri, 30 Sep 2011 14:22:32 -0400 Subject: [PATCH] Fix chunked input stream's available() method to never return -1. Change-Id: I6ea268e469675ef890010282dbe35ed5838cca73 http://code.google.com/p/android/issues/detail?id=20442 --- .../libcore/net/http/ChunkedInputStream.java | 5 +++- .../libcore/java/net/URLConnectionTest.java | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/luni/src/main/java/libcore/net/http/ChunkedInputStream.java b/luni/src/main/java/libcore/net/http/ChunkedInputStream.java index 380ed02de..91cff7acc 100644 --- a/luni/src/main/java/libcore/net/http/ChunkedInputStream.java +++ b/luni/src/main/java/libcore/net/http/ChunkedInputStream.java @@ -95,7 +95,10 @@ private void readChunkSize() throws IOException { @Override public int available() throws IOException { checkNotClosed(); - return hasMoreChunks ? Math.min(in.available(), bytesRemainingInChunk) : 0; + if (!hasMoreChunks || bytesRemainingInChunk == NO_CHUNK_YET) { + return 0; + } + return Math.min(in.available(), bytesRemainingInChunk); } @Override public void close() throws IOException { diff --git a/luni/src/test/java/libcore/java/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java index 345f3248a..acd3c137e 100644 --- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java +++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java @@ -1866,6 +1866,35 @@ public void testUrlContainsQueryButNoPath() throws Exception { assertEquals("GET /?query HTTP/1.1", request.getRequestLine()); } + // http://code.google.com/p/android/issues/detail?id=20442 + public void testInputStreamAvailableWithChunkedEncoding() throws Exception { + testInputStreamAvailable(TransferKind.CHUNKED); + } + + public void testInputStreamAvailableWithContentLengthHeader() throws Exception { + testInputStreamAvailable(TransferKind.FIXED_LENGTH); + } + + public void testInputStreamAvailableWithNoLengthHeaders() throws Exception { + testInputStreamAvailable(TransferKind.END_OF_STREAM); + } + + private void testInputStreamAvailable(TransferKind transferKind) throws IOException { + String body = "ABCDEFGH"; + MockResponse response = new MockResponse(); + transferKind.setBody(response, body, 4); + server.enqueue(response); + server.play(); + URLConnection connection = server.getUrl("/").openConnection(); + InputStream in = connection.getInputStream(); + for (int i = 0; i < body.length(); i++) { + assertTrue(in.available() >= 0); + assertEquals(body.charAt(i), in.read()); + } + assertEquals(0, in.available()); + assertEquals(-1, in.read()); + } + /** * Returns a gzipped copy of {@code bytes}. */