DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Overview of Android Networking Tools: Receiving, Sending, Inspecting, and Mock Servers
  • How a URL Shortening Application Works
  • Getting Started With Snowflake Snowpark ML: A Step-by-Step Guide
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests

Trending

  • Is the Model Context Protocol a Replacement for HTTP?
  • Segmentation Violation and How Rust Helps Overcome It
  • Key Considerations in Cross-Model Migration
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  1. DZone
  2. Data Engineering
  3. Data
  4. Migrating Retrofit To Ktor

Migrating Retrofit To Ktor

It is absolutely crucial to choose the most appropriate communication tool for exchanging data between Android applications and servers.

By 
Antoni Sanchez user avatar
Antoni Sanchez
·
Sep. 01, 23 · Opinion
Likes (1)
Comment
Save
Tweet
Share
4.3K Views

Join the DZone community and get the full member experience.

Join For Free

Communication between Android applications and servers is a critical aspect of application development, and choosing the right tool to perform this communication is fundamental. Until now, retrofit has been the standard for excellence.
However, in recent years, an interesting alternative has emerged: Ktor Client.

This library, developed by JetBrains entirely in Kotlin, offers a more modern and flexible way to make HTTP requests without relying on annotations, with a simpler and easier-to-understand syntax. Its plugins, such as authentication and serialization, exist as external dependencies, so you can install only the ones you need, making it a lightweight library. It is also cross-platform.

In this article, we will see practical examples that compare both clients and provide an overview for migrating any project. Please note: We assume the reader has basic knowledge of Retrofit, so we will not go into the details of the library.

Base Case

Let’s imagine the scenario where we have this basic retrofit setup: we use the Gson Converter, wrap the server response in Kotlin Result, and log the HTTP interaction using an interceptor.

Kotlin
 
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version" 
implementation "com.github.skydoves:retrofit-adapters-result:$retrofit_result_version" implementation "com.squareup.okhttp3:logging-interceptor:$logging_interceptor_version"


Kotlin
 
// creates okHttp engine with logger interceptor
val okHttp = OkHttpClient.Builder()
    .addInterceptor(HttpLoggingInterceptor()
        .apply {
            setLevel(
                HttpLoggingInterceptor.Level.BODY
            )
        })
    .build()

val retrofit = Retrofit.Builder()
// add base url for all request 
    .baseUrl(BASE_URL)
// add gson content negotiation 
    .addConverterFactory(GsonConverterFactory.create())
// add adapter to wrap response with result
    .addCallAdapterFactory(ResultCallAdapterFactory.create())
    .client(okHttp)
    .build()


How To Set Up Ktor

To migrate to Ktor, we would need these dependencies:

Kotlin
 
implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-client-okhttp:$ktor_version"
implementation "io.ktor:ktor-client-content-negotiation:$ktor_version"
implementation "io.ktor:ktor-serialization-gson:$ktor_version"
implementation "com.squareup.okhttp3:logging-interceptor:$logging_interceptor_version"


  • ktor-client-coreKtor’s main library includes interesting plugins such as HttpRequestRetry, HttpSend, and HttpCache, among others.
  • ktor-client-okhttp engine to process network requests. There are several android compatible engines: OkHttp (used in Retrofit, supports Http/2 and WebSockets), CIO (coroutine-based implementation), and Android (an engine that supports older versions of Android 1.x+)
  • ktor-client-content-negotiation plugin to serialize/deserialize content.
  • ktor-serialization-gson JSON serializer. There are other official alternatives such as Jackson and Kotlin’s serialization.

Once the libraries have been added, the equivalent Ktor configuration would be:

Kotlin
 
// creates Ktor client with OkHttp engine
val Ktor = HttpClient(OkHttp) {
    // default validation to throw exceptions for non-2xx responses  
    expectSuccess = true
     
    engine {
      // add logging interceptor            
        addInterceptor(HttpLoggingInterceptor().apply {
            setLevel(
                HttpLoggingInterceptor.Level.BODY
            )
        })
    }

    // set default request parameters
    defaultRequest {
      // add base url for all request
        url(BASE_URL)
    }

    // use gson content negotiation for serialize or deserialize 
    install(ContentNegotiation) {
        gson()
    }
}


Using the OkHttp engine allows us to reuse the interceptors we have created in our project.

How To Create the ApiService

In Retrofit, we define an interface, and each method must have an HTTP annotation that provides the request method. The library is in charge of generating the code at compile time. While Ktor provides equivalent functions to these annotations and we can reuse the existing interface (removing the retrofit annotations) so as not to break the contract, we are in charge of defining the implementation of these requests.

Kotlin
 
// Retrofit create a service
val service = retrofit.create<UserApiService>()

—-------—-------—-------—-------—-------—-------—-------—-------

// Ktor create a service
val service: UserApiService = UserApiServiceImpl(Ktor)


How To Make Requests

Now that we have the client configured let’s see some examples of how to make a GET request, how to manipulate the URL by replacing blocks with paths, and how to add query or header parameters, along with the different ways to send data.

GET requests – URL Manipulation

  • Retrofit
Kotlin
 
interface UserApiService {

        @GET("/user")
        suspend fun getUsers(): Result<Users>
        
        // Replacements blocks
        @GET("/user/{id}")
        suspend fun getUserById(@Path("id") id: Int): Result<User>
        
        // Query parameter
        @GET("/user")
        suspend fun getUsers(@Query("page") page: Int): Result<Users>
        
        // Complex query combinations
        @GET("/user")
        suspend fun getUsers(@QueryMap queries: Map<String, String>): Result<Users>
}


  • Ktor
Kotlin
 
class UserApiServiceImpl(private val Ktor: HttpClient) : UserApiService {

    suspend fun getUsers(): Result<Users> = runCatching {
        Ktor.get("/user").body()
    }

    // Replacements blocks
    suspend fun getUserById(id: Int): Result<User> = runCatching {
        Ktor.get("/user/$id").body()
    }

    // Query parameters
    suspend fun getUsers(page: Int): Result<Users> = runCatching {
        Ktor.get("/user") {
            parameter("page", page)
        }.body()
    }
    
    // Complex query combinations
    suspend fun getUsers(queries: Map<String, String>): Result<Users> = runCatching {
        Ktor.get("/user") {
            queries.forEach {
                parameter(it.key, it.value)
            }
        }.body()
    }
}


POST Requests – Sending Data

  • Retrofit
Kotlin
 
// request body
@POST("/user")
suspend fun createUser(@Body user: User): Result<User>

// request using x-www-form-urlencoded
@FormUrlEncoded
@POST("/user/edit")
suspend fun editUser(
    @Field("first_name") first: String,
    @Field("last_name") last: String
): Result<User>

// request multi-part
@Multipart
@POST("user/update")
suspend fun updateUser(@Part("photo") photo: MultipartBody.Part): Result<User>


  • Ktor
Kotlin
 
// request body
suspend fun createUser(user: User): Result<User> = runCatching {
    Ktor.post("/user") { setBody(user) }.body()
}

// request using x-www-form-urlencoded
suspend fun editUser(first: String, last: String): Result<User> = runCatching {
    Ktor.submitForm(
        url = "/user/edit",
        formParameters = Parameters.build {
            append("first_name", first)
            append("last_name", last)
        }
    ).body()
}

// request multi-part
suspend fun updateUser(photo: String): Result<User> = runCatching {
    Ktor.post("/user/update") {
        setBody(MultiPartFormDataContent(
            formData {
                append("photo", File(photo).readBytes())
            }
        ))
    }.body()
}


Headers

  • Retrofit
Kotlin
 
@Headers("Cache-Control: max-age=640000")
@GET("/user")
suspend fun getUsers(): Result<Users>

@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-App"
})
@GET("/user")
suspend fun getUsers(): Result<Users>

@GET("/user")
suspend fun getUsers(@Header("Authorization") auth: String): Result<Users>


  • Ktor
Kotlin
 
suspend fun getUsers(): Result<Users> = runCatching {
    Ktor.get("/user") {
        headers {
            append("header", "value")
            append("header", "value1") // this value will be appended to previous 
            appendIfNameAbsent("header", "value2") // this won't be added as name exists
            appendIfNameAndValueAbsent("header2", "value1") // this won't be added
        }
    }.body()
}


Conclusion

In short, the Ktor Client implementation is a bit more verbose, but at the same time, it is easy to understand and highly configurable. For example, we can type the URL, which, by having the requests in a structured way, facilitates the maintenance while providing greater control/security over the types used. It also allows us to create custom plugins that, among other things, make it easier to intercept calls.

And yes, it is a bit cumbersome to wrap the call each time in a runCatching or do .body() to get the payload of the response, but with this little extension, we avoid repeating ourselves.

Kotlin
 
suspend inline fun <reified R> HttpClient.getResult(
   urlString: String,
   builder: HttpRequestBuilder.() -> Unit = {}
): Result<R> = runCatching { get(urlString, builder).body() }


Engine Implementation Library Android (robot) Requests Data Types

Published at DZone with permission of Antoni Sanchez. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Overview of Android Networking Tools: Receiving, Sending, Inspecting, and Mock Servers
  • How a URL Shortening Application Works
  • Getting Started With Snowflake Snowpark ML: A Step-by-Step Guide
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!