Azizjon Kholmatov
Azizjon Kholmatov

Reputation: 1266

How to get response status in Retrofit (Kotlin)?

I am using Retrofit. Using Kotlin. I need to know the resonse status code. Like is it 200 or 500. How can I get it from the response ?

My Api class:

interface Api {
    @POST("user/code/check")
    fun checkSmsCode(@Body body: CheckCodeBody): Single<Response<Void>> }

This is how I am calling Api. But note that SERVE DOES NOT RETURN CODE FIELD IN RESPONSE BODY!

api.checkSmsCode(
   CheckCodeBody(
       code = code
   )
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({         
      //HOW TO CHECK STATUS RESPONSE STATUS CODE HERE???
    }, 
    { e ->
        when (e) {
            is IOException -> view?.showNoNetworkAlert()
            else -> view?.invalidCodeError()
        }
     }
).also {}

As I understood, in Java it was a easy peasy thing.

You just use response.code() or something similar and that's it. But how to achieve it in Kotlin?

Upvotes: 3

Views: 9875

Answers (3)

apksherlock
apksherlock

Reputation: 8371

If you haven't configure your retrofit request method to return a Response<*> you won't be able to have the response code. Example:

interface SomeApi{
 @POST("user/code/check")
fun checkSmsCode(@Body body: CheckCodeBody): Single<Response<String>> 
}

And after you finish your request:

.subscribe({
 //access response code here like : it.code()
 //and you can access the response.body() for your data
 //also you can ask if that response.isSuccessful
})

Upvotes: 0

Emmanuel Montt
Emmanuel Montt

Reputation: 376

yo need to use it

interface OnlineStoreService{

    @Headers("Content-Type: application/json","Connection: close")
    @POST
    fun getDevices(
            @Url url: String,
            @Header("Authorization") token: String,
            @Body apiParams: APIParams
    ): Observable<OnlineStoresInfo>

} 


.subscribe({ onlineStoresInfo ->   // or it -> where "it" it's your object response, in this case is my class OnlineStoresInfo

                    loading.value = false
                    devices.value = onlineStoresInfo.devices

                }, { throwable ->
                    Log.e(this.javaClass.simpleName, "Error getDevices ", throwable)
                    loading.value = false
                    error.value = context.getString(R.string.error_information_default_html)
                })

.subscribe({ it -> 
// code
}, { throwable ->
 //code
})

Upvotes: 0

Brent
Brent

Reputation: 778

so your on response should look something like this

      override fun onResponse(call: Call<MyModel>?, response: Response<MyModel>?) {
           //
      }
 })

then inside that you should just to able to do

      override fun onResponse(call: Call<MyModel>?, response: Response<MyModel>?) {
           response.code()
      }
 })

is this what your talking about?

Upvotes: 0

Related Questions