Android: How to retain the errorBody() in retrofit

2020-04-19 07:01发布

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条回答
家丑人穷心不美
2楼-- · 2020-04-19 07:45

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.

查看更多
登录 后发表回答