HttpUtils.kt (2631B)
1 /* 2 * This file is part of GNU Taler 3 * (C) 2024 Taler Systems S.A. 4 * 5 * GNU Taler is free software; you can redistribute it and/or modify it under the 6 * terms of the GNU General Public License as published by the Free Software 7 * Foundation; either version 3, or (at your option) any later version. 8 * 9 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 * A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License along with 14 * GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 package net.taler.common 18 19 import io.ktor.client.HttpClient 20 import io.ktor.client.engine.okhttp.OkHttp 21 import io.ktor.client.plugins.HttpRedirect 22 import io.ktor.client.plugins.HttpTimeout 23 import io.ktor.client.plugins.HttpTimeoutConfig.Companion.INFINITE_TIMEOUT_MS 24 import io.ktor.client.plugins.contentnegotiation.ContentNegotiation 25 import io.ktor.client.plugins.logging.ANDROID 26 import io.ktor.client.plugins.logging.LogLevel 27 import io.ktor.client.plugins.logging.Logger 28 import io.ktor.client.plugins.logging.Logging 29 import io.ktor.http.HttpMethod 30 import io.ktor.serialization.kotlinx.json.json 31 import kotlinx.serialization.json.Json 32 33 fun getDefaultHttpClient( 34 withJson: Boolean = true, 35 timeoutMs: Long? = null, 36 followRedirect: Boolean = false, 37 logging: Boolean = true, 38 ): HttpClient = HttpClient(OkHttp) { 39 expectSuccess = true 40 followRedirects = followRedirect 41 engine { 42 config { 43 retryOnConnectionFailure(true) 44 } 45 } 46 install(ContentNegotiation) { 47 if (withJson) { 48 json(Json { 49 encodeDefaults = false 50 ignoreUnknownKeys = true 51 }) 52 } 53 } 54 install(HttpTimeout) { 55 requestTimeoutMillis = if (timeoutMs != null && timeoutMs > 0) { 56 timeoutMs 57 } else { 58 INFINITE_TIMEOUT_MS 59 } 60 61 socketTimeoutMillis = INFINITE_TIMEOUT_MS 62 connectTimeoutMillis = INFINITE_TIMEOUT_MS 63 } 64 install(HttpRedirect) { 65 checkHttpMethod = !followRedirect 66 } 67 install(Logging) { 68 logger = Logger.ANDROID 69 level = if (logging) LogLevel.INFO else LogLevel.NONE 70 } 71 } 72 73 fun String.toHttpMethod(): HttpMethod? = when(this) { 74 "GET" -> HttpMethod.Get 75 "POST" -> HttpMethod.Post 76 "PUT" -> HttpMethod.Put 77 "PATCH" -> HttpMethod.Patch 78 "DELETE" -> HttpMethod.Delete 79 "OPTIONS" -> HttpMethod.Options 80 else -> null 81 }