Skip to content

Instantly share code, notes, and snippets.

@droid-ash
Created January 4, 2021 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save droid-ash/6cbf5865f363555e0da890eb35e84d56 to your computer and use it in GitHub Desktop.
Save droid-ash/6cbf5865f363555e0da890eb35e84d56 to your computer and use it in GitHub Desktop.
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