Skip to content

Commit 38a9270

Browse files
committed
HttpRequest: handle chunked encoding
1 parent a6aee24 commit 38a9270

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

src/org/netpreserve/jwarc/HttpRequest.java

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,19 @@ private static HttpRequest parse(ReadableByteChannel channel, ByteBuffer buffer,
8787
copyTo.write(buffer.duplicate());
8888
}
8989
MessageHeaders headers = parser.headers();
90-
Long contentLength;
91-
try {
92-
contentLength = headers.first("Content-Length").map(Long::parseLong).orElse(null);
93-
} catch (NumberFormatException e) {
94-
if (strict) throw new IOException("Invalid Content-Length header", e);
95-
contentLength = null;
90+
MessageBody body;
91+
if (headers.contains("Transfer-Encoding", "chunked")) {
92+
body = new ChunkedBody(channel, buffer);
93+
} else {
94+
Long contentLength;
95+
try {
96+
contentLength = headers.first("Content-Length").map(Long::parseLong).orElse(0L);
97+
} catch (NumberFormatException e) {
98+
if (strict) throw new IOException("Invalid Content-Length header", e);
99+
contentLength = null;
100+
}
101+
body = LengthedBody.createFromContentLength(channel, buffer, contentLength);
96102
}
97-
LengthedBody body = LengthedBody.createFromContentLength(channel, buffer, contentLength);
98103
HttpRequest request = new HttpRequest(parser.method(), parser.target(), parser.version(), headers, body);
99104
request.serializedHeader = headerBytes;
100105
return request;

test/org/netpreserve/jwarc/HttpRequestTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,24 @@ public void serializeHeaderShouldPreserveExactly() throws IOException {
2525
assertEquals(header, new String(request.serializeHeader(), US_ASCII));
2626
}
2727

28+
@Test
29+
public void chunkedEncodingRequestShouldDecodeBody() throws IOException {
30+
String header = "POST /submit HTTP/1.1\r\n" +
31+
"Host: example.org\r\n" +
32+
"Transfer-Encoding: chunked\r\n\r\n";
33+
String chunkedBody = "4\r\nWiki\r\n" +
34+
"5\r\npedia\r\n" +
35+
"0\r\n\r\n";
36+
String message = header + chunkedBody;
37+
38+
HttpRequest request = HttpRequest.parse(Channels.newChannel(new ByteArrayInputStream(message.getBytes(US_ASCII))));
39+
40+
assertEquals("POST", request.method());
41+
assertEquals("/submit", request.target());
42+
assertEquals(Optional.of("chunked"), request.headers().first("Transfer-Encoding"));
43+
assertEquals("Wikipedia", new String(IOUtils.readNBytes(request.body().stream(), 32), US_ASCII));
44+
}
45+
2846
@Test(expected = IllegalArgumentException.class)
2947
public void invalidVersionShouldThrow() {
3048
new HttpRequest.Builder("GET", "/").version(MessageVersion.WARC_1_0);

0 commit comments

Comments
 (0)