Http Client
Communicating with server.
WebClient Implementation Overview
Purpose:
The web.client.kt
file provides a reusable HTTP client implementation for making network requests in your KMM application. It handles authentication, content negotiation, and error handling using Ktor.
Ktor Client Configuration:
The ktorClient
function creates a Ktor HTTP client and configures it with the following plugins:
Auth
: Enables bearer token authentication.loadTokens
: Retrieves the initial access and refresh tokens from the data store.refreshTokens
: Handles token refresh when the access token expires.
ContentNegotiation
: Configures JSON serialization and deserialization using a custom JSON configuration.WebSockets
: Enables WebSocket support (if needed).HttpTimeout
: Configures HTTP request timeouts (optional).
Additional Features:
getAuth
: Retrieves authentication information from the data store.cleanupAuth
: Manages bearer token cleanup or refresh.applyFilter
: Allows you to apply custom filters to HTTP responses.refreshToken
: Handles token refresh logic.
Usage:
Create a
AuthCredentials
object: Provide the necessary credentials for authentication.Call
ktorClient
: Pass theAuthCredentials
object to thektorClient
function to create an HTTP client instance.Use the HTTP client: Use the created client to make HTTP requests, such as
get
,post
,put
, ordelete
.
Example:
Kotlin
Key Points:
The
web.client.kt
file provides a well-structured and reusable HTTP client implementation.It handles authentication, content negotiation, and error handling automatically.
You can customize the client's behavior by modifying the configuration or adding custom plugins.
The provided example demonstrates how to create and use the HTTP client in your KMM application.
By understanding the web.client.kt
file, you can effectively make network requests in your KMM applications and handle authentication and data exchange efficiently.
Last updated