|
1 | 1 | package com.oursky.authgear.net |
2 | 2 |
|
| 3 | +import java.io.ByteArrayInputStream |
| 4 | +import java.io.ByteArrayOutputStream |
3 | 5 | import java.io.InputStream |
4 | 6 | import java.io.OutputStream |
5 | 7 | import java.net.HttpURLConnection |
@@ -32,12 +34,24 @@ open class DefaultHTTPClient: HTTPClient { |
32 | 34 |
|
33 | 35 | val statusCode = conn.responseCode |
34 | 36 | val responseHeaders = conn.headerFields |
35 | | - val responseBody: InputStream |
| 37 | + |
| 38 | + // Determine which input stream to read from. |
| 39 | + val originalInputStream: InputStream? |
36 | 40 | if (conn.errorStream != null) { |
37 | | - responseBody = conn.errorStream |
| 41 | + originalInputStream = conn.errorStream |
38 | 42 | } else { |
39 | | - responseBody = conn.inputStream |
| 43 | + originalInputStream = conn.inputStream |
| 44 | + } |
| 45 | + |
| 46 | + // Since we have to call conn.disconnect() in this method, |
| 47 | + // the original input stream will be closed when this method returns. |
| 48 | + // Therefore, we copy the original input stream to a byte buffer. |
| 49 | + // It should not be a problem as the response body should be small. |
| 50 | + val byteArrayOutputStream = ByteArrayOutputStream() |
| 51 | + originalInputStream?.use { |
| 52 | + this.transferTo(originalInputStream, byteArrayOutputStream) |
40 | 53 | } |
| 54 | + val responseBody = ByteArrayInputStream(byteArrayOutputStream.toByteArray()) |
41 | 55 |
|
42 | 56 | val response = HTTPResponse(statusCode, responseHeaders, responseBody) |
43 | 57 | return response |
|
0 commit comments