不废话直接上代码
在环境支持Kotlin的基础上添加如下依赖
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
1.将请求返回的json转为bean类
(目前AS的Gson插件无法转译为kotlin的bean类,于是先生成javabean,再用AS一键转为Kotlin)
转换方法:
转kotlin后得到的Bean类:
package com.demo.kotlin.kotlindemo
/**
* Created by Administrator on 2018/5/11 0011.
*/
class CaseListBean {
/**
* code : 100
* msg : 查询成功
* data : {"count":3,"data":[{"case_id":35,"case_name":"测试案件2","addtime":"1514526115","status":7},{"case_id":31,"case_name":"测试案件","addtime":"1513936149","status":6},{"case_id":2,"case_name":"天安门房子案","addtime":"1514610028","status":6}]}
*/
var code: Int = 0
var msg: String? = null
var data: DataBeanX? = null
class DataBeanX {
/**
* count : 3
* data : [{"case_id":35,"case_name":"测试案件2","addtime":"1514526115","status":7},{"case_id":31,"case_name":"测试案件","addtime":"1513936149","status":6},{"case_id":2,"case_name":"天安门房子案","addtime":"1514610028","status":6}]
*/
var count: Int = 0
var data: List<DataBean>? = null
class DataBean {
/**
* case_id : 35
* case_name : 测试案件2
* addtime : 1514526115
* status : 7
*/
var case_id: Int = 0
var case_name: String? = null
var addtime: String? = null
var status: Int = 0
}
}
}
2.定义接口类 APIService
主要定义接口的请求类型,详细的请求地址,和所需的参数
interface APIService{
//post,加在统一接口后面的详细接口
@POST("Caseapi/caseList")
//采用map的形式传参
fun getIpMsgByMap(@QueryMap map: Map<String, Int>): Call<CaseListBean>
@POST("Caseapi/caseList")
//采用固定键值对的形式传参
fun getIpMsgByParams(@Query ("user_id")user_id:Int,@Query ("userrole")userrole:Int,@Query ("company_id")company_id:Int): Call<CaseListBean>
}
3.在Application定义Retrofit对象并return该对象创建的service
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://test.xj.wangshangfayuan.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val ipService = retrofit.create(APIService::class.java)
4.通过Application拿到service请求网络
方式一:(map传参)
var map = HashMap<String, Int>()
map.put("userrole", 1)
map.put("user_id",55)
map.put("company_id",5)
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://demo.wangshangfayuan.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val ipService = retrofit.create(APIService::class.java)
ipService.getIpMsgByMap(map).enqueue(object: Callback<CaseListBean> {
override fun onResponse(call: Call<CaseListBean>?, response: Response<CaseListBean>?) {
println(response!!.body().data!!.data!!.get(0).case_name)
}
override fun onFailure(call: Call<CaseListBean>?, t: Throwable?) {
println("error")
}
})
方式二:固定参数传参
ipService.getIpMsgByParams(1,28,5).enqueue(object: Callback<CaseListBean> {
override fun onResponse(call: Call<CaseListBean>?, response: Response<CaseListBean>?) {
println(response!!.body().data!!.count)
}
override fun onFailure(call: Call<CaseListBean>?, t: Throwable?) {
println("error")
}
})