Android: How to retain the errorBody() in retrofit response?

a 夏天 提交于 2019-12-24 21:42:40

问题


I want to get the errorBody's error message, which I do by calling errorBody().string() (tried with errorbody().byteStream() too). But no matter what, after reading it out, the response errorbody's message will be null. It's not an option to save out the string to a static variable, but the project requires to check the response multiple times in different scenarios. My question is how to get the errorBody's message without clearing it out?


回答1:


errorBody is of type ResponseBody is from OkHttp. The docs make it clear you can only read from it once. This is because it is a stream, not already stored in memory --

A one-shot stream from the origin server to the client application with the raw bytes of the response body. Each response body is supported by an active connection to the webserver. This imposes both obligations and limits on the client application.

You only get to call .string() (or other methods that access the stream once). If you need to access the value more than once you have to save it the first time you access it and use that cached value in later code. It doesn't have to be a static variable, it can be a regular variable, but you are responsible for passing it around your code just like any other piece of data you use in multiple places.



来源:https://stackoverflow.com/questions/49557988/android-how-to-retain-the-errorbody-in-retrofit-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!