I'm developing an Android App using Retrofit & OkHttp.
The backend i'm facing is of questionable quality:
It bypasses the http-error-code-system for a "homemade" solution.
Instead of sending the appropriate error code, it returns a HTTP-200 with a body containing { "errorcode" : 404 }.
Since i can't change the backend, i'd like to cleanup this mess as soon as it enters my app; a Okhttp interceptor seems like the right place:
okHttpClient
.addInterceptor(responseBodyInterceptor(json))
[...]
.build()
@Throws(BackendError::class)
private fun responseBodyInterceptor(json: Json) = Interceptor { chain ->
chain.proceed(chain.request()).also { response ->
// retrieving the whole body here - similar to the official logging interceptor
val body = response.peekBody(Long.MAX_VALUE).string()
val bodyObject = json.parseToJsonElement() as? JsonObject
val errorcode = (bodyObject?.get("errorcode") as? JsonPrimitive)?.content
if (errorcode != null) throw BackendError(errorcode)
}
}
I'm now looking for a more elegant way to do this. My issue here is that i'm parsing the complete network response at once. I'd like to parse it somewhat similar to a stream. Is this possible?