Madalina Chis
Madalina Chis

Reputation: 51

Can`t solve "Content-Length and stream length disagree" error

I get an error while trying to execute the following code:

 fun parseErrorCodes(response: Response<*>): List<String> {
        val errorCodes: MutableList<String> = ArrayList()
        try {
            val listType = object : TypeToken<ArrayList<ApiError>>() {
            }.type
            val errorJson = JsonParser().parse(response.errorBody().string()).asJsonObject.get("response")
            if (errorJson.isJsonArray) {
                val errors = Gson().fromJson<List<ApiError>>(errorJson, listType)
                for (apiError in errors) {
                    errorCodes.add(apiError.errorCode)
                }
                return errorCodes
            } else {
                errorCodes.add(Gson().fromJson(errorJson, ApiError::class.java).errorCode)
                return errorCodes
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return errorCodes
    }

The error occurs at the line : val errorJson = JsonParser().parse(response.errorBody().string()).asJsonObject.get("response")

Can someone help me to solve this error?

Upvotes: 2

Views: 2046

Answers (1)

Madalina Chis
Madalina Chis

Reputation: 51

I found the answer to my question. The problem was that I was trying to parse the response for the API twice, first time to show the error messages and then to get the error codes to handle them for future validations.

This is how my code looks:

ErrorHandler.showError(activity, response)
val errorCodes = ErrorHandler.parseErrorCodes(response)
handleErrorCodes(errorCodes)

So, both methods showError and parseErrorCodes were working with the API response.

Upvotes: 3

Related Questions