diff --git a/project.properties b/project.properties index baeadd7..fafceaf 100644 --- a/project.properties +++ b/project.properties @@ -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 diff --git a/src/main/com/jdbernard/net/HttpContext.groovy b/src/main/com/jdbernard/net/HttpContext.groovy index 5b1e078..fbe3162 100644 --- a/src/main/com/jdbernard/net/HttpContext.groovy +++ b/src/main/com/jdbernard/net/HttpContext.groovy @@ -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