Android Retrofit

new-silvermoon/awesome-android-agent-skills/.github/skills/concurrency_and_networking/android-retrofit

作者 new-silvermoon82900eacc8dbe13de93c6310af27b9df4b2bd2f6無授權條款收錄於 2026年10月9日更新於 2026年10月9日

Expert guidance on setting up and using Retrofit for type-safe HTTP networking in Android. Covers service definitions, coroutines, OkHttp configuration, and Hilt integration.

AI 產生的概覽

提供在 Android 中建置 Retrofit 型別安全 HTTP 網路層的指引,涵蓋服務定義、協程、OkHttp 與 Hilt。

功能
此技能為使用 Retrofit 建置 Android 網路層提供參考指引與程式碼範例。內容涵蓋動態 URL 路徑與查詢參數、請求主體、表單編碼與 multipart 請求、靜態與動態標頭、suspend 函式與 Response 回傳型別、Hilt 模組設定,以及儲存庫層的錯誤處理。它產出的是說明性指示與 Kotlin 程式碼片段,而非可執行的指令碼。
適用情境
適用於使用 Retrofit 實作或檢閱 Android 應用程式 HTTP 網路層的情境。適合解答關於服務介面、OkHttp 用戶端設定、使用 Hilt 進行相依性注入,或處理網路回應與錯誤的問題。
執行需求
不包含指令碼或工具,僅為說明性指示。套用其中的範例需要具備使用 Kotlin、Retrofit、OkHttp 與 Hilt 的 Android 專案,並在執行時需要網路存取。

Android Networking with Retrofit

Instructions

When implementing network layers using Retrofit, follow these modern Android best practices (2025).

1. URL Manipulation

Retrofit allows dynamic URL updates through replacement blocks and query parameters.

  • Dynamic Paths: Use {name} in the relative URL and @Path("name") in parameters.
  • Query Parameters: Use @Query("key") for individual parameters.
  • Complex Queries: Use @QueryMap Map<String, String> for dynamic sets of parameters.
kotlin
interface SearchService {    @GET("group/{id}/users")    suspend fun groupList(        @Path("id") groupId: Int,        @Query("sort") sort: String?,        @QueryMap options: Map<String, String> = emptyMap()    ): List<User>}

2. Request Body & Form Data

You can send objects as JSON bodies or use form-encoded/multipart formats.

  • @Body: Serializes an object using the configured converter (JSON).
  • @FormUrlEncoded: Sends data as application/x-www-form-urlencoded. Use @Field.
  • @Multipart: Sends data as multipart/form-data. Use @Part.
kotlin
interface UserService {    @POST("users/new")    suspend fun createUser(@Body user: User): User
    @FormUrlEncoded    @POST("user/edit")    suspend fun updateUser(        @Field("first_name") first: String,        @Field("last_name") last: String    ): User
    @Multipart    @PUT("user/photo")    suspend fun uploadPhoto(        @Part("description") description: RequestBody,        @Part photo: MultipartBody.Part    ): User}

3. Header Manipulation

Headers can be set statically for a method or dynamically via parameters.

  • Static Headers: Use @Headers.
  • Dynamic Headers: Use @Header.
  • Header Maps: Use @HeaderMap.
  • Global Headers: Use an OkHttp Interceptor.
kotlin
interface WidgetService {    @Headers("Cache-Control: max-age=640000")    @GET("widget/list")    suspend fun widgetList(): List<Widget>
    @GET("user")    suspend fun getUser(@Header("Authorization") token: String): User}

4. Kotlin Support & Response Handling

When using suspend functions, you have two choices for return types:

  1. Direct Body (User): Returns the deserialized body. Throws HttpException for non-2xx responses.
  2. Response<User>: Provides access to the status code, headers, and error body. Does NOT throw on non-2xx results.
kotlin
@GET("users")suspend fun getUsers(): List<User> // Throws on error
@GET("users")suspend fun getUsersResponse(): Response<List<User>> // Manual check

5. Hilt & Serialization Configuration

Provide your Retrofit instances as singletons in a Hilt module.

kotlin
@Module@InstallIn(SingletonComponent::class)object NetworkModule {
    @Provides    @Singleton    fun provideJson(): Json = Json {        ignoreUnknownKeys = true        coerceInputValues = true    }
    @Provides    @Singleton    fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder()        .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY })        .connectTimeout(30, TimeUnit.SECONDS)        .build()
    @Provides    @Singleton    fun provideRetrofit(okHttpClient: OkHttpClient, json: Json): Retrofit = Retrofit.Builder()        .baseUrl("https://api.github.com/")        .client(okHttpClient)        .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))        .build()}

6. Error Handling in Repositories

Always handle network exceptions in the Repository layer to keep the UI state clean.

kotlin
class GitHubRepository @Inject constructor(private val service: GitHubService) {    suspend fun getRepos(username: String): Result<List<Repo>> = runCatching {        // Direct body call throws HttpException on 4xx/5xx        service.listRepos(username)    }.onFailure { exception ->        // Handle specific exceptions like UnknownHostException or SocketTimeoutException    }}

7. Checklist

  • Use suspend functions for all network calls.
  • Prefer Response<T> if you need to handle specific status codes (e.g., 401 Unauthorized).
  • Use @Path and @Query instead of manual string concatenation for URLs.
  • Configure OkHttpClient with logging (for debug) and sensible timeouts.
  • Map API DTOs to Domain models to decouple layers.

來源與署名

來源:new-silvermoon/awesome-android-agent-skills位於.github/skills/concurrency_and_networking/android-retrofit提交82900ea

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架