Skip to content

Commit

Permalink
feat: write HTTP Response body to file (#5643)
Browse files Browse the repository at this point in the history
for downloading and other usages
  • Loading branch information
MukjepScarlet authored Feb 16, 2025
1 parent 4684ff6 commit 8eb0f6a
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions src/main/kotlin/net/ccbluex/liquidbounce/api/core/HttpClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okio.BufferedSource
import okio.buffer
import okio.sink
import java.io.File
import java.io.InputStream
import java.util.concurrent.TimeUnit
Expand Down Expand Up @@ -81,21 +83,8 @@ object HttpClient {
response
}

suspend fun download(url: String, file: File, agent: String = DEFAULT_AGENT) = withContext(Dispatchers.IO) {
val request = createRequest(url, HttpMethod.GET, agent)

client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw HttpException(HttpMethod.GET, url, response.code, "Failed to download file")
}

file.outputStream().use { output ->
response.body.byteStream().use { input ->
input.copyTo(output)
}
}
}
}
suspend fun download(url: String, file: File, agent: String = DEFAULT_AGENT) =
request(url, HttpMethod.GET, agent).toFile(file)

}

Expand All @@ -118,6 +107,10 @@ inline fun <reified T> Response.parse(): T {
}
}

fun Response.toFile(file: File) = use { response ->
file.sink().buffer().use(response.body.source()::readAll)
}

fun String.asJson() = toRequestBody(HttpClient.JSON_MEDIA_TYPE)
fun String.asForm() = toRequestBody(HttpClient.FORM_MEDIA_TYPE)

Expand Down

0 comments on commit 8eb0f6a

Please sign in to comment.