fix FileNotFoundException when response code is 4xx or 5xx
This commit is contained in:
@@ -36,7 +36,10 @@ suspend fun apiRequest(
|
|||||||
val url = URL(SERVER + uri)
|
val url = URL(SERVER + uri)
|
||||||
with(url.openConnection() as HttpURLConnection) {
|
with(url.openConnection() as HttpURLConnection) {
|
||||||
requestMethod = method
|
requestMethod = method
|
||||||
headerFields["Content-Type"] = listOf("Application/json")
|
doInput = true
|
||||||
|
if (method == "POST" || method == "PUT") {
|
||||||
|
setRequestProperty("Content-Type", "application/json")
|
||||||
|
doOutput = true
|
||||||
val data = when (body) {
|
val data = when (body) {
|
||||||
is String -> {
|
is String -> {
|
||||||
body
|
body
|
||||||
@@ -48,15 +51,18 @@ suspend fun apiRequest(
|
|||||||
val wr = OutputStreamWriter(outputStream)
|
val wr = OutputStreamWriter(outputStream)
|
||||||
wr.write(data)
|
wr.write(data)
|
||||||
wr.flush()
|
wr.flush()
|
||||||
|
}
|
||||||
|
if (responseCode >= 400) {
|
||||||
|
BufferedReader(InputStreamReader(errorStream)).use {
|
||||||
|
val response = it.readText()
|
||||||
|
onFail?.invoke(response)
|
||||||
|
}
|
||||||
|
return@with
|
||||||
|
}
|
||||||
//response
|
//response
|
||||||
BufferedReader(InputStreamReader(inputStream)).use {
|
BufferedReader(InputStreamReader(inputStream)).use {
|
||||||
val response = it.readText()
|
val response = it.readText()
|
||||||
if (responseCode == 200) {
|
|
||||||
onOk?.invoke(response)
|
onOk?.invoke(response)
|
||||||
} else {
|
|
||||||
onFail?.invoke(response)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
eventually?.invoke()
|
eventually?.invoke()
|
||||||
|
|||||||
Reference in New Issue
Block a user