Last active
September 6, 2020 21:48
-
-
Save Alqueraf/1c913ce7a719eb7b775c8538519b5609 to your computer and use it in GitHub Desktop.
Medium Ktor Client configuration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun createHttpClient(): HttpClient { | |
return HttpClient(OkHttp) { | |
// Json | |
install(JsonFeature) { | |
serializer = KotlinxSerializer(json) | |
} | |
// Logging | |
install(Logging) { | |
logger = object : Logger { | |
override fun log(message: String) { | |
Log.v("Ktor", message) | |
} | |
} | |
level = LogLevel.ALL | |
} | |
// Timeout | |
install(HttpTimeout) { | |
requestTimeoutMillis = 15000L | |
connectTimeoutMillis = 15000L | |
socketTimeoutMillis = 15000L | |
} | |
// Apply to All Requests | |
defaultRequest { | |
parameter("api_key", "some_api_key") | |
// Content Type | |
if (this.method != HttpMethod.Get) contentType(ContentType.Application.Json) | |
accept(ContentType.Application.Json) | |
} | |
// Optional OkHttp Interceptors | |
engine { | |
addInterceptor(CurlInterceptor(Loggable { Log.v("Curl", it) })) | |
} | |
} | |
} | |
private val json = Json { | |
ignoreUnknownKeys = true | |
isLenient = true | |
encodeDefaults = false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment