- 優(yōu)點(diǎn):簡(jiǎn)單方便欢揖,擴(kuò)展多
- 缺點(diǎn):中文文檔少豺型,使用要在Android版本5及以上(sdk 19+)(不知道以后會(huì)不會(huì)有改進(jìn)毁涉,現(xiàn)在是這樣)
用法
- 添加依賴
//Fuel
//Android使用
implementation 'com.github.kittinunf.fuel:fuel-android:1.16.0'
//Gson解析
implementation 'com.github.kittinunf.fuel:fuel-gson:1.16.0'
GET網(wǎng)絡(luò)請(qǐng)求用法(有三種寫(xiě)法,我就列出一條)
//get屡萤,返回String
Fuel.get("https://httpbin.org/get").responseString { request, response, result ->
//返回參數(shù)
result.fold({ d ->
//返回成功珍剑,處理數(shù)據(jù)
}, { err ->
//請(qǐng)求失敗,執(zhí)行錯(cuò)誤處理
})
}
有時(shí)候我們返回的時(shí)候希望直接轉(zhuǎn)化成實(shí)體類
- 要轉(zhuǎn)化的實(shí)體類
package com.em.testfuel
data class User(val name: String, val age: Int) {
}
- 請(qǐng)求
Fuel.get(url).responseObject<User> { request, response, result ->
result.fold({
Log.e("test",it.name)
},{
Log.e("test", it.message)
})
}
有時(shí)候我們需要這樣寫(xiě)
data class User(val name: String, val age: Int) {
class Deserializer : ResponseDeserializable<User> {
override fun deserialize(content: String): User? {
return Gson().fromJson(content, User::class.javaObjectType)
}
}
}
Fuel.get(url).responseObject(User.Deserializer()) { request, response, result ->
result.fold({
Log.e("test",it.name)
},{
Log.e("test", it.message)
})
}
POST網(wǎng)絡(luò)請(qǐng)求
舉兩個(gè)例子:
- body是form-data
val url2 = "http://192.168.0.101:8888/saveuser"
Fuel.post(url2, listOf("name" to "李四","age" to 18)).responseObject<User> { request, response, result ->
result.fold({
Log.e("test",it.name)
},{
Log.e("test", it.message)
})
}
- body是raw
val url3 = "http://192.168.0.101:8889/name"
val requestBean = User("王五", 22)
val requestData = Gson().toJson(requestBean)
val type = mutableMapOf<String, String>()
type["Content-Type"] = "application/json"
Fuel.post(url3)
.body(requestData)
.header(type)
.responseString { _, _, result ->
result.fold({
Log.e("test", it)
}, {
Log.e("test", it.message)
})
}