下面给出 Fuel 2.x 的 "开箱即用" 封装类,同时支持:
- POST JSON (
application/json) - POST 表单 (
application/x-www-form-urlencoded) - 文件上传 (
multipart/form-data)
复制即用 ,零配置 ,自动切回主线程回调。
✅ 1. 添加依赖(build.gradle)
kotlin
implementation 'com.github.kittinunf.fuel:fuel:2.3.1'
implementation 'com.github.kittinunf.fuel:fuel-android:2.3.1' // 自动切主线程
implementation 'com.github.kittinunf.fuel:fuel-gson:2.3.1' // JSON 自动序列化
✅ 2. 封装类(copy 即用)
kotlin
object HttpFuel {
/* ① POST JSON ---------------------------------------------------------- */
fun postJson(
url: String,
body: Any, // 任意对象 / Map / String
onSuccess: (String) -> Unit,
onError: (String) -> Unit
) {
Fuel.post(url)
.jsonBody(Gson().toJson(body)) // 自动转 JSON
.responseString { _, _, result ->
val (data, error) = result
if (error == null) onSuccess(data!!)
else onError(error.message)
}
}
/* ② POST 表单 ---------------------------------------------------------- */
fun postForm(
url: String,
params: List<Pair<String, Any?>>,
onSuccess: (String) -> Unit,
onError: (String) -> Unit
) {
Fuel.post(url, params.filterNotNull())
.responseString { _, _, result ->
val (data, error) = result
if (error == null) onSuccess(data!!)
else onError(error.message)
}
}
/* ③ 上传文件(可带表单字段) ------------------------------------------- */
fun upload(
url: String,
params: List<Pair<String, Any?>> = emptyList(),
file: File,
fileKey: String = "file",
onProgress: (Long, Long) -> Unit = { _, _ -> },
onSuccess: (String) -> Unit,
onError: (String) -> Unit
) {
Fuel.upload(url, Method.POST, params)
.source { _, _ -> file }
.name { fileKey }
.progress { read, total -> onProgress(read, total) }
.responseString { _, _, result ->
val (data, error) = result
if (error == null) onSuccess(data!!)
else onError(error.message)
}
}
}
✅ 3. 使用示例(Activity / ViewModel)
kotlin
/* 3.1 发 JSON */
HttpFuel.postJson(
url = "http://192.168.1.100:8809/sync/one688",
body = mapOf("ben" to ben) // 任意对象/Map
) { resp -> Log.d("JSON", resp) }
/* 3.2 发表单 */
HttpFuel.postForm(
url = "http://192.168.1.100:8809/sync/one688",
params = listOf("id" to 0, "tlite" to "text")
) { resp -> Log.d("FORM", resp) }
/* 3.3 上传文件 + 进度 */
val file = File(cacheDir, "a.jpg")
HttpFuel.upload(
url = "http://192.168.1.100:8809/upload",
params = listOf("user" to "tom"),
file = file,
onProgress = { read, total ->
val pct = (read * 100 / total).toInt()
Log.d("UP", "$pct%")
}
) { resp -> Log.d("UP", "完成:$resp") }
✅ 4. 自动切回主线程
fuel-android 模块已保证 回调在主线程 ,可直接更新 UI 。
✅ 5. 自定义全局配置(可选)
kotlin
FuelManager.instance.basePath = "http://192.168.1.100:8809/"
FuelManager.instance.baseHeaders = mapOf("token" to "abc123")
🔚 一句话总结
引入 fuel + fuel-android + fuel-gson → 复制 HttpFuel 单例 →
postJson / postForm / upload 三种调用 开箱即用 ,主线程回调 ,零配置发请求 。