Skip to content

Instantly share code, notes, and snippets.

@vengateshm
Last active September 24, 2021 17:48
Show Gist options
  • Save vengateshm/24f7df6ad7cc76d1f5485af640eb6063 to your computer and use it in GitHub Desktop.
Save vengateshm/24f7df6ad7cc76d1f5485af640eb6063 to your computer and use it in GitHub Desktop.
Ktor client on Android
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlinx-serialization'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.android.vengateshm.ktorclientsample"
minSdk 21
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1'
implementation 'io.ktor:ktor-client-android:1.5.0'
implementation 'io.ktor:ktor-client-serialization:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1'
implementation 'io.ktor:ktor-client-logging-jvm:1.5.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import io.ktor.client.*
import io.ktor.client.engine.android.*
import io.ktor.client.features.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.logging.*
import io.ktor.client.features.observer.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
private const val TIMEOUT = 60_000
class MainActivity : AppCompatActivity() {
private val tag = MainActivity::class.java.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val httpClient = HttpClient(Android) {
install(DefaultRequest) {
header(HttpHeaders.ContentType, ContentType.Application.Json)
}
install(ResponseObserver) {
onResponse {
Log.d(tag, "HTTP Status : ${it.status}")
}
}
install(JsonFeature) {
serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
prettyPrint = true
ignoreUnknownKeys = true
isLenient = true
})
engine {
connectTimeout = TIMEOUT
socketTimeout = TIMEOUT
}
}
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Log.d(tag, message)
}
}
level = LogLevel.ALL
}
}
lifecycleScope.launch(Dispatchers.IO) {
try {
val response =
httpClient.get<List<ToDo>>(urlString = "https://jsonplaceholder.typicode.com/todos")
Log.d(tag, "Response $response")
} catch (e: Exception) {
Log.d(tag, "Error ${e.message!!}");
}
}
}
}
@Serializable
data class ToDo(
val userId: Int,
val id: Int,
val title: String,
val completed: Boolean
)
buildscript {
ext.kotlin_version = '1.5.31'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31"
classpath "org.jetbrains.kotlin:kotlin-serialization:${kotlin_version}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment