我正在使用Kotlin Android应用程序调用API端点。 在此API调用中,我返回了一个字节数组。 我想知道是否有一种将字节数组转换为pdf文件并将其保存在手机下载文件夹中的方法。
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
}