A tiny http client for Kotlin/Android. Only 90 lines of code. This is wrapper around native HttpURLConnection.
val request = HttpRequest(
url = "https://httpbin.org/get",
parameters = mapOf("name" to "Alex")
)
request.json<HttpBin> { result, response ->
println(result)
}
val request = HttpRequest(
url = "https://httpbin.org/post",
method = Method.POST,
parameters = mapOf("name" to "Alex"),
headers = mapOf("User-Agent" to "HttpRequest")
)
request.json<HttpBin> { result, response ->
println(response.exception)
println(response.success)
println(result)
}
val request = HttpRequest("https://httpbin.org/get", config = {
it.readTimeout = 1000
it.setRequestProperty("User-Agent", "HttpRequest")
})
HttpRequest uses Kotlinx Serialization
for Json.
@Serializable data class HttpBin(
val args: Map<String, String>? = null,
val form: Map<String, String>? = null,
val headers: Map<String, String>? = null
)
val request = HttpRequest("https://httpbin.org/get")
request.json<HttpBin> { result, response ->
println(result)
}
Custom decoder
HttpRequest.json = Json {
ignoreUnknownKeys = false
}
HttpRequest("https://httpbin.org/get").response {
println(Xml.parse(it.body))
}
HttpRequest makes request and parsing asynchronously.
Use runOnUiThread
to change UI.
request.json<Post> { post, response ->
runOnUiThread {
titleTextView.text = post.title
}
}
- Add JitPack
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
}
- Add dependencies
implementation 'com.github.mezhevikin:http-request-kotlin:0.0.5'
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1'
- Add plugin
plugins {
id 'org.jetbrains.kotlin.plugin.serialization' version '1.7.20'
}
๐ HttpRequest for Swift/iOS
โ๏ธ Buy me a coffee