Skip to content

Instantly share code, notes, and snippets.

@ashish410
Created Jan 4, 2021
Embed
What would you like to do?
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