HttpContext: Added support for Transfer-Encoding: chunked

This commit is contained in:
Jonathan Bernard 2013-09-21 02:28:24 -05:00
parent 3fcc28d4ed
commit 3929968af1
2 changed files with 36 additions and 4 deletions

View File

@ -1,6 +1,6 @@
#Sun, 18 Aug 2013 15:42:51 -0500
#Sat, 21 Sep 2013 02:27:46 -0500
name=jdb-util
version=2.1
version=2.2
lib.local=true
build.number=0
build.number=8

View File

@ -94,6 +94,8 @@ public class HttpContext {
result.status = line.split(/\s/)[1]
line = reader.readLine().trim()
boolean isChunked = false
while(line) {
def m = (line =~ /Content-Length: (\d+)/)
if (m) bytesExpected = m[0][1] as int
@ -101,8 +103,11 @@ public class HttpContext {
m = (line =~ /Set-Cookie: ([^=]+=[^;]+);.+/)
if (m) this.cookie = m[0][1]
m = (line =~ /Transfer-Encoding: chunked/)
if (m) isChunked = true
result.headers << line
line = reader.readLine() }
line = reader.readLine().trim() }
if (bytesExpected) {
StringBuilder sb = new StringBuilder()
@ -111,6 +116,33 @@ public class HttpContext {
result.responseTime = System.currentTimeMillis() - startTime
try { result.content = new JsonSlurper().parseText(sb.toString()) }
catch (Exception e) { result.content = sb.toString() } }
else if (isChunked) {
// Read chunks
StringBuilder sb = new StringBuilder()
while (true) {
line = reader.readLine().trim()
if (line == "0") break // end of chunks
// length of this chunk
else bytesExpected = Integer.parseInt(line.split(';')[0], 16)
for (int i = 0; i < bytesExpected; i++) {
sb.append(reader.read() as char) }
// Read CRLF
reader.readLine() }
// Read any following headers.
line = reader.readLine().trim()
while (line) {
result.headers << line
line = reader.readLine().trim() }
result.responseTime = System.currentTimeMillis() - startTime
try { result.content = new JsonSlurper().parseText(sb.toString()) }
catch (Exception e) { result.content = sb.toString() } }
else