Skip to content

Commit 3f9c80f

Browse files
authored
Fix incorrect usage of HttpURLConnection input stream #219
ref DEV-3096
2 parents 9bd9658 + 70f1e2f commit 3f9c80f

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

sdk/src/main/java/com/oursky/authgear/net/DefaultHTTPClient.kt

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.oursky.authgear.net
22

3+
import java.io.ByteArrayInputStream
4+
import java.io.ByteArrayOutputStream
35
import java.io.InputStream
46
import java.io.OutputStream
57
import java.net.HttpURLConnection
@@ -32,12 +34,24 @@ open class DefaultHTTPClient: HTTPClient {
3234

3335
val statusCode = conn.responseCode
3436
val responseHeaders = conn.headerFields
35-
val responseBody: InputStream
37+
38+
// Determine which input stream to read from.
39+
val originalInputStream: InputStream?
3640
if (conn.errorStream != null) {
37-
responseBody = conn.errorStream
41+
originalInputStream = conn.errorStream
3842
} 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)
4053
}
54+
val responseBody = ByteArrayInputStream(byteArrayOutputStream.toByteArray())
4155

4256
val response = HTTPResponse(statusCode, responseHeaders, responseBody)
4357
return response

0 commit comments

Comments
 (0)