I'm hitting an API Endpoint with a Kotlin Android app. In this API call I'm returning a byte Array. What I would like to see is a way to convert the byte array to a pdf file and save it in the phones download folder.
private suspend fun getIDCard(sessionID: String?, carriermemid: String?): ByteArray? {
var results: String = ""
val postData = "{\"sessionid\": \" $sessionID\"}"
val outputStreamWriter: OutputStreamWriter
var byteArray: ByteArray? = null
val url: URL = URL(idURL + carriermemid)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
try {
conn.setRequestProperty(apiConfig.typeKey, apiConfig.typeValueJSON)
conn.setRequestProperty("Accept", "application/json")
conn.setRequestProperty("sessionid", sessionID)
conn.requestMethod = apiConfig.methodGet
val responseCode: Int = conn.responseCode
println("Response Code :: $responseCode")
//returning 404
return if (responseCode == HttpURLConnection.HTTP_OK) {// connection ok
var out: ByteArrayOutputStream? = ByteArrayOutputStream()
val `in`: InputStream = conn.inputStream
var bytesRead: Int
val buffer = ByteArray(1024)
while (`in`.read(buffer).also { bytesRead = it } > 0) {
out!!.write(buffer, 0, bytesRead)
}
out!!.close()
byteArray = out.toByteArray()
return byteArray
} else {
return byteArray
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
conn.disconnect()
}
return byteArray
}