android-retrofit by new-silvermoon/awesome-android-agent-skills
npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill android-retrofit在使用 Retrofit 实现网络层时,请遵循以下现代 Android 最佳实践(2025年)。
Retrofit 允许通过替换块和查询参数动态更新 URL。
{name},在参数中使用 @Path("name")。@Query("key")。@QueryMap Map<String, String>。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>
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
您可以将对象作为 JSON 请求体发送,或使用表单编码/多部分格式。
application/x-www-form-urlencoded 格式发送数据。使用 @Field。multipart/form-data 格式发送数据。使用 @Part。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
}
可以为方法静态设置请求头,或通过参数动态设置。
@Headers。@Header。@HeaderMap。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
}
使用 suspend 函数时,返回类型有两种选择:
User):返回反序列化的响应体。对于非 2xx 响应会抛出 HttpException。Response<User>:提供对状态码、请求头和错误体的访问。对于非 2xx 结果不会抛出异常。@GET("users")
suspend fun getUsers(): List<User> // 出错时抛出异常
@GET("users")
suspend fun getUsersResponse(): Response<List<User>> // 手动检查
在 Hilt 模块中将您的 Retrofit 实例作为单例提供。
@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()
}
始终在仓库层处理网络异常,以保持 UI 状态清晰。
class GitHubRepository @Inject constructor(private val service: GitHubService) {
suspend fun getRepos(username: String): Result<List<Repo>> = runCatching {
// 直接返回体的调用在 4xx/5xx 时会抛出 HttpException
service.listRepos(username)
}.onFailure { exception ->
// 处理特定异常,如 UnknownHostException 或 SocketTimeoutException
}
}
suspend 函数。Response<T>。@Path 和 @Query 而不是手动拼接 URL 字符串。OkHttpClient 配置日志记录(用于调试)和合理的超时时间。每周安装量
138
代码仓库
GitHub 星标数
565
首次出现
2026年1月29日
安全审计
安装于
opencode128
codex125
claude-code100
gemini-cli94
github-copilot89
kimi-cli86
When implementing network layers using Retrofit , follow these modern Android best practices (2025).
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.
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> }
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.
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
}
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.
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
}
When using suspend functions, you have two choices for return types:
User): Returns the deserialized body. Throws HttpException for non-2xx responses.Response<User>: Provides access to the status code, headers, and error body. Does NOT throw on non-2xx results.@GET("users")
suspend fun getUsers(): List<User> // Throws on error
@GET("users")
suspend fun getUsersResponse(): Response<List<User>> // Manual check
Provide your Retrofit instances as singletons in a Hilt module.
@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()
}
Always handle network exceptions in the Repository layer to keep the UI state clean.
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
}
}
suspend functions for all network calls.Response<T> if you need to handle specific status codes (e.g., 401 Unauthorized).@Path and @Query instead of manual string concatenation for URLs.OkHttpClient with logging (for debug) and sensible timeouts.Weekly Installs
138
Repository
GitHub Stars
565
First Seen
Jan 29, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode128
codex125
claude-code100
gemini-cli94
github-copilot89
kimi-cli86
飞书OpenAPI Explorer:探索和调用未封装的飞书原生API接口
37,900 周安装