-
-
Save droid-ash/6cbf5865f363555e0da890eb35e84d56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class RequestTask(private val req: Request) : Runnable { | |
override fun run() { | |
try { | |
val conn = request() | |
val parsedResponse = parseResponse(conn) | |
req.sendResponse(parsedResponse, null) | |
} catch (e: IOException) { | |
req.sendResponse(null, e) | |
} | |
} | |
@Throws(IOException::class) | |
private fun request(): HttpURLConnection { | |
val url = URL(req.url) | |
val conn = url.openConnection() as HttpURLConnection | |
val method = req.method | |
conn.requestMethod = method | |
for ((key, value) in req.header) { | |
conn.setRequestProperty(key, value) | |
} | |
if (req.body != null) { | |
val outputStream = conn.outputStream | |
outputStream.write(req.body) | |
} | |
conn.connect() | |
return conn | |
} | |
@Throws(IOException::class) | |
private fun parseResponse(conn: HttpURLConnection): Response { | |
try { | |
val bos = ByteArrayOutputStream() | |
val status = conn.responseCode | |
val validStatus = status in 200..299 | |
val inpStream = if (validStatus) conn.inputStream else conn.errorStream | |
var read: Int | |
var totalRead = 0 | |
val buf = ByteArray(bufferSize) | |
while (inpStream.read(buf).also { read = it } != -1) { | |
bos.write(buf, 0, read) | |
totalRead += read | |
} | |
return Response(bos.toByteArray()) | |
} finally { | |
conn.disconnect() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment