how get json by retrofit2 in kotlin

440 views Asked by At

I use retrofit2 to connect to an api and receive data The data is nested

D/OkHttp: {"success":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9}}

If the data is as in the example above, it will be received without any problems But if it is as follows, it gives an error

D/OkHttp: {"message":"Unauthenticated."}

I do this for the first example

data class Response(var success : AutoLoginUser)
data class AutoLoginUser(var token: String)
...
...
...
Log.w("OK FROM SERVER", response.body()!!.success!!.token)

And for the second example, I do the following

data class UserDetails(var message : String)
...
...
...
Log.w("OK FROM SERVER", response.body()!!.message)

The error I get for the second example

D/OkHttp: <-- 401 Unauthorized http://192.168.1.8/api/details (252ms)
Host: 192.168.1.8
Date: Wed, 02 Dec 2020 09:01:03 GMT
Connection: close
X-Powered-By: PHP/7.4.12
Cache-Control: no-cache, private
Date: Wed, 02 Dec 2020 09:01:03 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *
D/OkHttp: {"message":"Unauthenticated."}
<-- END HTTP (30-byte body)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ir.i9i.splendor, PID: 5740
java.lang.NullPointerException
    at ir.i9i.splendor.Profile$getUserDetails$1.onResponse(Profile.kt:39)
    at   retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
1

There are 1 answers

0
ʍѳђઽ૯ท On BEST ANSWER

You can handle it with errorBody() in your onResponse() method of Retrofit:

if (response.code() == 200 && response.isSuccessful) {

                       // do whatever you want when the response is 200 and isSuccessful

                    } else {

                        if (response.errorBody() != null) {

                            val jsonObj =
                                JSONObject(response.errorBody()!!.charStream().readText())
                            val getMessage = jsonObj.getString("message")
                                    
                             // Here get the message and print it out
                            showSnackBar(yourActivity, getMessage)

                        }
                    }

Because you retrieved 401 error response, you'll be able to handle such errors in onResponse() method.