Bhavya Sikka
12/06/2023, 10:27 AM@Throws(Throwable::class)
suspend inline fun <reified T> request(
endpoint: String,
headers: Map<String, String>? = null,
queryParams: Map<String, String>?,
requestBody: Any?,
method: HttpMethod
): Result<NetworkResponse<T>> {
try {
val response = httpClient.request {
this.method = method
url {
this.protocol = URLProtocol.HTTPS
this.host = endpoint
}
requestBody?.run {
setBody(this)
}
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
queryParams?.forEach {
parameter(it.key, it.value)
}
}
Bhavya Sikka
12/06/2023, 10:28 AMval httpClientProvider = HttpClientProviderImpl()
open val httpClient: HttpClient by lazy {
httpClientProvider.httpClient {
install(ContentNegotiation) {
json(
Json {
prettyPrint = true
isLenient = true
}
)
}
}
}
Bhavya Sikka
12/06/2023, 10:28 AMclass HttpClientProviderImpl : HttpClientProvider {
override fun httpClient(config: HttpClientConfig<*>.() -> Unit): HttpClient {
return HttpClient()
}
}
interface HttpClientProvider {
fun httpClient(config: HttpClientConfig<*>.() -> Unit): HttpClient
}
Pablichjenkov
12/06/2023, 11:38 AMBhavya Sikka
12/06/2023, 6:06 PMendpoint = "<http://api.github.com/users/mralexgray/repos|api.github.com/users/mralexgray/repos>",
Pablichjenkov
12/06/2023, 7:24 PMChrimaeon
12/07/2023, 10:04 AM/users/mralexgray/repos
shouldn’t be part of the host
if that is endpoint
you are assigning. Maybe iOS engine is more strict then the one on Android. I’d rather use a url parser and split up the endpoint to all the required parameters.Chrimaeon
12/07/2023, 10:05 AMBhavya Sikka
12/08/2023, 5:21 AMval segments = ("users" + "mralexgray" + "repos").urlToSegment()
val response = httpClient.request {
url {
this.protocol = URLProtocol.HTTPS
this.host = endpoint //insert host here
this.path(*segments.toTypedArray())
}
Shoaib khalid
12/19/2023, 10:58 AMurlToSegment()
basically?Shoaib khalid
12/19/2023, 10:59 AMBhavya Sikka
01/02/2024, 4:52 AMfun String?.urlToSegment(): List<String> {
if (this.isNullOrBlank()) return listOf()
return this.split("/")
}