Basic use of network request framework Retrofit (Kotlin)

It was introduced a few days ago

Kotlin's basic usage and base class encapsulation, MVVM and DataBinding

LiveData secondary packaging, easy to use in Kotlin

The Android project uses it as a dependency

Puppy: The above can basically realize a complete project
Murong Haizhu: What do you think is missing?
Puppy: What’s missing, it’s enough
Murong Haizhu: Then what do you use for network requests? OKHTTP? I don’t think it fits.
Puppy: Alright, let’s use Retrofit
Murong Haizhu: How to use it?
Puppy egg: walking

First import dependencies, how to write a dependency by yourself see above If
there is a request, the analysis will also be included!

    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'

Secondly, it can be used, just write the relevant data in the method

Murong Haizhu: Don't make trouble!

Retrofit is a request framework based on OKHTTP encapsulation. It can be understood as just wearing a layer of clothes for OKHTTP, and OKHTTP is still active inside. The clothes are just for better looks, and the request body is constructed through dynamic registration and annotations.

Here we take the open API of Android as an example. This Demo runs normally.

GET request

insert image description here

fun getData(){
    
    
        val mGson = GsonBuilder()
            .setLenient() // 设置GSON的非严格模式setLenient()
            .create()
        Retrofit.Builder()
            .baseUrl("https://www.wanandroid.com/")
            .addConverterFactory(GsonConverterFactory.create(mGson))
            .build()
            .create(getData::class.java)
            .getJsonData()
            .enqueue(object : Callback<JsonsRootBean?> {
    
    
                override fun onResponse(call: Call<JsonsRootBean?>, response: Response<JsonsRootBean?>) {
    
    
                    //请求成功走这里
                    val body: JsonsRootBean? = response.body()
                }
                override fun onFailure(call: Call<JsonsRootBean?>, t: Throwable) {
    
    
                    //请求失败走这里
                    Log.e(TAG, "onFailure: $t")
                }
            })
    }
    interface getData {
    
    
        @GET("article/list/1/json")
        fun getJsonData(
            //这里面放参数
        ): Call<JsonsRootBean>
    }

POST request

insert image description here

fun postData(){
    
    
        var mGson = GsonBuilder()
            .setLenient() // 设置GSON的非严格模式setLenient()
            .create()
        Retrofit.Builder()
            .baseUrl("https://www.wanandroid.com/")
            .addConverterFactory(GsonConverterFactory.create(mGson))
            .build()
            .create(postData::class.java)
            .getJsonData(
                "我是Token",
                "我是其他的数据")
            .enqueue(object : Callback<JsonsRootBean?> {
    
    
                override fun onResponse(call: Call<JsonsRootBean?>, response: Response<JsonsRootBean?>) {
    
    
                    val body = response.body()
                }
                override fun onFailure(call: Call<JsonsRootBean?>, t: Throwable) {
    
    
                    Log.e(TAG, "onFailure: $t")
                }
            })
    }

    interface postData{
    
    
        @FormUrlEncoded
        @POST("article/cutStore")
        fun getJsonData(
            @Header("apikey") apikey: String,
            @Field("articleid") articleid: String?,
        ): Call<JsonsRootBean>
    }

Entity class: Because Kotlin is used, there is no need for a get set method, so don’t forget to instantiate it at the end

class JsonsRootBean(
    private var data: Data? = null,
    private var errorcode: Int = 0,
    private var errormsg: String? = null
) : Serializable

class Datas(
    var apklink: String? = null,
    var audit: Int = 0,
    var author: String? = null,

    var canedit: Boolean = false,

    var chapterid: Int = 0,

    var chaptername: String? = null,
    var collect: Boolean = false,

    var courseid: Int = 0,
    var desc: String? = null,

    var descmd: String? = null,

    var envelopepic: String? = null,
    var fresh: Boolean = false,
    var host: String? = null,
    var id: Int = 0,
    var link: String? = null,

    var nicedate: String? = null,

    var nicesharedate: String? = null,
    var origin: String? = null,
    var prefix: String? = null,

    var projectlink: String? = null,

    var publishtime: Int = 0,

    var realsuperchapterid: Int = 0,

    var selfvisible: Int = 0,

    var sharedate: Int = 0,

    var shareuser: String? = null,

    var superchapterid: Int = 0,

    var superchaptername: String? = null,
    //var tags: ArrayList<String>? = arrayListOf(),
    var title: String? = null,
    var type: Int = 0,

    var userid: Int = 0,
    var visible: Int = 0,
    var zan: Int = 0,
) : Serializable

class Data(
    var curpage: Int = 0,
    var datas: List<Datas>? = null,
    var offset: Int = 0,
    var over: Boolean = false,

    var pagecount: Int = 0,
    var size: Int = 0,
    var total: Int = 0,
) : Serializable


At a glance, this code is not much different from OKHTTP, don't worry, look carefully

insert image description here
Under normal circumstances, these parts can be taken out separately for centralized management, decoupling!

Let’s go through the process, compare it with OKHTTP, and look at the request data part. Get and post are taken out separately in the form of comments. For ttp, you need .add(" "," ") every time, and you want to get it separately Come out, broadly, are you writing a small entity class or a map? (Actually, you can pass FormBody) ttp needs to go to Gson every time the request is successful, fit is not needed, and .body is directly used

Murong Haizhu: What about the others?

Puppy egg:. . . . , Well, except for some official support for this and that, it’s nothing to use, but the amount of code and the way of writing are really much simpler to use. Praise!

Dog egg tip:
There may be a parsing error when requesting: JsonSyntaxException,
don’t panic
1. According to the log error
insert image description here
, I have obviously pointed out which parameter parsing error is wrong. Just change it according to the prompt. If you can’t change it, check whether the parameter is useful It is generally used on the Internet, comment out the useless ones, hehehe

2. Even if there is no useful information in the log
, it will point out the type of error, and guess the error based on the type. Confirm with the back-end partner and change it to be consistent, or if there is no direct evidence, do a packet capture to see. Find someone with screenshots, Ori

Guess you like

Origin blog.csdn.net/As_thin/article/details/123816373