- 优点:简单方便,扩展多
- 缺点:中文文档少,使用要在Android版本5及以上(sdk 19+)(不知道以后会不会有改进,现在是这样)
用法
- 添加依赖
//Fuel
//Android使用
implementation 'com.github.kittinunf.fuel:fuel-android:1.16.0'
//Gson解析
implementation 'com.github.kittinunf.fuel:fuel-gson:1.16.0'
GET网络请求用法(有三种写法,我就列出一条)
//get,返回String
Fuel.get("https://httpbin.org/get").responseString { request, response, result ->
//返回参数
result.fold({ d ->
//返回成功,处理数据
}, { err ->
//请求失败,执行错误处理
})
}
有时候我们返回的时候希望直接转化成实体类
- 要转化的实体类
package com.em.testfuel
data class User(val name: String, val age: Int) {
}
- 请求
Fuel.get(url).responseObject<User> { request, response, result ->
result.fold({
Log.e("test",it.name)
},{
Log.e("test", it.message)
})
}
有时候我们需要这样写
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网络请求
举两个例子:
- 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)
})
}
网友评论