感谢:JakeWharton Retrofit库 https://github.com/square/retrofit
聚合数据提供数据支持 https://www.juhe.cn/
这是一份很详细的 Retrofit 2.0 使用教程Carson_Ho
本文仅为学习记录,望指正。
一、Retrofit 使用步骤
1.在Module中的build.gradle添加Retofit库及网络权限。
a~ You might also need rules for OkHttp and Okio which are dependencies of this library.
b~ AndroidManifest.xml
2.创建一个实体类来接受服务区返回的数据。数据来自聚合数据新闻数据post/get。格式如下
{
"reason":"成功的返回",
"result":{
"stat":"1",
"data":[
{
"uniquekey":"6db0ec6dff2990dbe5c7a202e2f3335f",
"title":"广交会第二期在广州琶洲会展中心开幕",
"date":"2018-10-24 09:12",
"category":"头条",
"author_name":"南方网",
"url":"http://mini.eastday.com/mobile/181024091211566.html",
"thumbnail_pic_s":"http://02imgmini.eastday.com/mobile/20181024/20181024091211_2a0753f869b236df1c40fe7b9f137ae9_1_mwpm_03200403.jpg"
},
{
"uniquekey":"515bacc3fd69c67749cb29110d5993dc",
"title":"火箭军某旅新兵营开展“新老兵结对共成长”活动",
"date":"2018-10-24 09:10","category":"头条",
"author_name":"中国军网",
"url":"http://mini.eastday.com/mobile/181024091051786.html",
"thumbnail_pic_s":"http://07imgmini.eastday.com/mobile/20181024/20181024091051_3534d8968e2f5bd39d3ab9a6c94993b0_1_mwpm_03200403.jpg"
}
]
},
"error_code":0
}
实体类如下:
data class TopNewsBean(
val reason: String,
val result: Result,
val error_code: Int
)
data class Result(
val stat: String,
val data: MutableList
)
data class Data(
val uniquekey: String,
val title: String,
val date: String,
val category: String,
val author_name: String,
val url: String,
val thumbnail_pic_s: String,
val thumbnail_pic_s02: String,
val thumbnail_pic_s03: String
)
3.创建用于描述网络请求的接口
interface GetRequestInterface {
@GET("toutiao/index?type=top&key=29e6b7c4d8953edbdbbb2b1e45b55ba2")
fun getCall(): Call
// @GET注解的作用:采用Get方法发送网络请求
// getCall() = 接收网络请求数据的方法
// 其中返回类型为Call<*>,*是接收数据的类(即上面定义的TopNewsBean类)
@POST("toutiao/index?")
@FormUrlEncoded
fun postCall(@Field("type")mTop:String,@Field("key")mKey:String): Call
// 需要配合@Field 向服务器提交需要的字段
//@FormUrlEncoded 表示请求体是一个表单数据
}
}
4.创建Retrofit对象,实例化接口,发送网络请求
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sendRequest()
}
private fun sendRequest() {
//创建retrofit 对象
val mRetrofit = Retrofit.Builder()
.baseUrl("http://v.juhe.cn/")
.addConverterFactory(GsonConverterFactory.create())
.build()
//实例化网络接口
val mGetRequestInterface = mRetrofit.create(GetRequestInterface::class.java)
//发送Get网络请求
mGetRequestInterface.getCall().enqueue(object : Callback {
override fun onFailure(call: Call, t: Throwable) {
Log.i("Test", "连接失败")
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful){
val results = response.body()?.result?.data?.get(0)
show.text = results?.title
Log.i("Test", results?.title)
}
}
})
//发送Post网络请求
mGetRequestInterface.postCall("top","29e6b7c4d8953edbdbbb2b1e45b55ba2").enqueue(object : Callback {
override fun onFailure(call: Call, t: Throwable) {
Log.i("Test", "连接失败")
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful){
val results = response.body()?.result?.data?.get(0)
show.text = results?.title
Log.i("Test", results?.title)
}
}
})
}
}
在写这篇文章的时候,微风细雨007博主向我推荐了一个网络请求# Fuel,Kotlin 网络框架支持很多新特性可以看一下。
插曲---- 面试题思考:GET和POST两种基本请求方法的区别
下一篇(二)Retrofit 网络框架的封装