Android:如何在改型响应中保留errorBody()? [英] Android: How to retain the errorBody() in retrofit response?

查看:64
本文介绍了Android:如何在改型响应中保留errorBody()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取errorBody的错误消息,我可以通过调用errorBody().string()来做到这一点(也尝试使用errorbody().byteStream()).但是无论如何,在读出后,响应错误体的消息将为空.不能将字符串保存到静态变量中,但是该项目需要在不同情况下多次检查响应.我的问题是如何在不清除errorBody的情况下获取它的消息?

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?

推荐答案

errorBody 的类型为

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 --

从源服务器到客户端应用程序的一键式流与响应主体的原始字节.每个响应主体是与Web服务器的活动连接所支持.这强加了客户应用程序的义务和限制.

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.

您只能调用 .string()(或其他一次访问该流的方法).如果您需要多次访问该值,则必须在第一次访问时保存它,并在以后的代码中使用该缓存的值.它不一定是 static 变量,它可以是常规变量,但是您有责任像在多个地方使用的任何其他数据一样在代码中传递它.

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.

这篇关于Android:如何在改型响应中保留errorBody()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆