Android使用Kotlin+Retrofit+Rxjava實現簡單的網路請求

淡淡的香菸發表於2020-12-16

kotlin在使用中也有一段時間了,這裡分享一下最基本的使用Kotlin+Retrofit+Rxjava實現網路請求:這裡以wanAndroidApi為例。

1.請求文章列表
2.具體程式碼:
/**
 * 獲取首頁文章列表
 */
private fun getArtList() {
    val retrofit = Retrofit.Builder()
        .baseUrl(Constant.BASE_SERVER_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()
    val server: ApiServer = retrofit.create(ApiServer::class.java)
    server.articleLists(1).enqueue(object : Callback<List<ArticleListBean>> {
        override fun onFailure(call: Call<List<ArticleListBean>>, t: Throwable) {
        }

        override fun onResponse(
            call: Call<List<ArticleListBean>>,
            response: Response<List<ArticleListBean>>
        ) {
            Log.d("data----", gson!!.toJson(response.body()))
        }

    })
}

3.interface ApiServer {

//首頁文章列表
@GET("/article/list/{page}/json")
fun articleList(@Path("page") page:Int) : Observable<BaseResult<ArticleListBean>>

}

4.請求結果基類

/**
 * @作者: njb
 * @時間: 2020/12/3 15:37
 * @描述:
 */
class BaseResult <T>{
    val errorCode: String = ""
    val errorMsg: String = ""
    val success: Boolean = false
    var data: T? = null
}

5.文章列表實體類:ArticleListBean

class ArticleListBean {
    var datas: MutableList<DatasBean>? = null
    class DatasBean {
        /**
         * apkLink :
         * author : Jetictors
         * chapterId : 232
         * chapterName : 入門及知識點
         * collect : false
         * courseId : 13
         * desc :
         * envelopePic :
         * fresh : true
         * id : 3226
         * link : http://www.cnblogs.com/Jetictors/tag/Kotlin/
         * niceDate : 4小時前
         * origin :
         * projectLink :
         * publishTime : 1533522956000
         * superChapterId : 232
         * superChapterName : Kotlin
         * tags : []
         * title : Kotlin 系列文章
         * type : 0
         * userId : -1
         * visible : 1
         * zan : 0
         */

        var apkLink: String? = null         // 文章uri
        var author: String? = null          //
        var chapterId: Int = 0              //
        var chapterName: String? = null
        var isCollect: Boolean = false
        var courseId: Int = 0
        var desc: String? = null
        var envelopePic: String? = null
        var isFresh: Boolean = false
        var id: Int = 0
        var link: String? = null
        var niceDate: String? = null
        var origin: String? = null
        var projectLink: String? = null
        var publishTime: Long = 0
        var superChapterId: Int = 0
        var superChapterName: String? = null
        var title: String? = null
        var type: Int = 0
        var userId: Int = 0
        var visible: Int = 0
        var zan: Int = 0
        var tags: List<*>? = null
        var isSelect: Boolean  = false
    }
}

6.執行結果如下:

相關文章