0

I have a xampp server connected to my android app. When I perform an api call, it would return either a response code 200 or a response code 400. If the response code is 200, I'm able to get the body of the response.

Here is the response body:

{"message": "User was created."}

However, I'm unable to get the response body when the code is 400.

It is null.

This is my interface:

@POST("api/user/createUser.php")
suspend fun register(@Body details : JsonObject) : Response<JsonElement>

This is how I call it:

val service = Server.ApiClient.createService(ServerInterface::class.java)
        
        CoroutineScope(Dispatchers.IO).launch {

            try {
                val response = service.register(details)
                Log.wtf("Message",response.body().toString())
            }
            catch (e : Exception){
                Log.wtf("Error",e.message)
            }
        }

Here is the log :

Response code 200:

E/Message: {"message":"User was created."}

Response code 400:

E/Message: null

Does anybody know how to solve this ?

1 Answers1

0

If I remember correctly, retrofit handles response codes outside 200-399 range as errors, so the message should be available using response.errorBody() instead of response.body().

omiwrench
  • 90
  • 1
  • 9
  • When I call .toString() on the `response.errorBody()` , the String is like this : `okhttp3.ResponseBody$Companion$asResponseBody$1@559aed4` – Binish Mathew Jan 12 '21 at 15:44
  • @BinishMathew that's because `errorBody()` returns an object of type `ResponseBody`. You can call the [`string()`](https://square.github.io/okhttp/4.x/okhttp/okhttp3/-response-body/string/) method on it to get the response body as a String: `response.errorBody().string()` – user2340612 Jan 12 '21 at 16:42
  • That worked. Thanks @user2340612 but the string() is flagged as `Inappropriate blocking method call` . What does that mean ? – Binish Mathew Jan 12 '21 at 16:57
  • Basically that warning is saying that the method may potentially block the thread by reading the entire response body into memory, vanishing the potential benefit of coroutines. [Here](https://stackoverflow.com/questions/58680028/how-to-make-inappropriate-blocking-method-call-appropriate) you may find more info – user2340612 Jan 12 '21 at 17:02