How to make an API request in Kotlin?

前端 未结 4 2124
悲哀的现实
悲哀的现实 2021-01-31 15:29

I am extremely new to Kotlin and APIs in general and can\'t find the syntax to create an API request using this language. I am creating a mobile version of a website so I\'m usi

4条回答
  •  忘掉有多难
    2021-01-31 15:57

    I have create a sample API call using retrofit 2. Firstly, add these libraries in gradle

    implementation "com.squareup.retrofit2:retrofit:2.3.0"
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"
    implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
    

    then create a class to configure Retrofit 2, say Connect.kt

    class Connect {
    
        companion object {
    
            private fun getRetrofit(Url:String):Retrofit {
                return Retrofit.Builder()
                        .addCallAdapterFactory(
                                RxJava2CallAdapterFactory.create())
                        .addConverterFactory(
                                GsonConverterFactory.create())
                        .baseUrl(Url)
                        .build()
            }
    
            fun getApiData():Retrofit{
                val retrofitApi = getRetrofit(Url.BASE_URL)
                return retrofitApi
            }
    
            fun callApi():CallApi{
                val retrofitCall = getApiData()
                return retrofitCall.create(CallApi::class.java)
            }
    
        }
    }
    

    I have created Url in Url class say Url.kt

    class Url {
        companion object {
            const val BASE_URL = "your base url"
            const val URL = "your url"
        }
    }
    

    Created an interface for Api call

        interface CallApi {
    
            @GET(Url.URL)
    //query needed if there is any query
            fun getApi(@Query("limit") limit: Int):
    //model class is needed                
    Observable
        }
    

    Create a model class according to your response, sample response is

    {
        "data": {
            "children": [
                {
                    "data": {
                        "author": "",
                         "thumbnail":"",
                          "title":""
                         }
                     }]
              }
     }
    

    for creating its model class, create an object say, Model

    object Model {
        data class Result(val data: Data)
        data class Data(val children: List)
        data class Children(val data: Datas)
        data class Datas(val author: String,val thumbnail: String,val title: String)
    }
    

    Then create a boiler plate class to perform data fetch from api which can be called from any activity

    class ApiData {
        companion object {
            const val count = 10
            val api by lazy { Connect.callApi() }
            var disposable: Disposable? = null
            fun apiData(callback:Response){
                disposable = api.getApi(count)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe ({
                            result ->
                            callback.data(result,true)
                        }, { error ->
                            error.printStackTrace()
                        })
    
            }
    
        }
        interface Response {
            fun data(data:Model.Result,status:Boolean)
        }
    }
    

    now it can be called from activity like,

    ApiData.apiData( object :ApiData.Response{
        override fun data(data: Model.Result, status: Boolean) {
            if(status){
                val items:List = data.data.children
            }
        }
    
    })
    

提交回复
热议问题