从Okhttp消费单次ResponseBody导致与改造问题 [英] Consuming One-Shot ResponseBody from Okhttp causes issues with Retrofit
问题描述
我为了我使用与Okhttp拦截器的改造,以检测是否我的OAuth令牌已过期。如果令牌已经到期,我想申请一个新的令牌,再次尝试请求,然后发送响应改造。
I am using an Retrofit with an Okhttp interceptor in order to detect if my oauth token has expired. If the token has expired, I want to request a new token, try the request again, then send that response to Retrofit.
下面是我的拦截器类:
public class CustomInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = chain.proceed(request);
if (response.body().string().contains(Constants.TOKEN_AUTH_ERROR_MESSAGE)) {
Log.v("retrofit_error", "token expired");
//get current token, create headers
OAuthTokenResponse expiredToken = SharedPreferencesUtil.getOAuthToken();
OAuthTokenResponse newOauthToken = RestClient.getInstance().getTokenService().refreshOauthToken(expiredToken.getRefreshToken());
//store new token, return
SharedPreferencesUtil.saveOAuthToken(newOauthToken);
// create a new request and modify it accordingly using the new token
Request.Builder newRequestBuilder = request.newBuilder()
.removeHeader("Authorization");
Request newRequest = newRequestBuilder.addHeader("Authorization", SharedPreferencesUtil.getOAuthToken().getAccessToken()).build();
// retry the request
return chain.proceed(newRequest);
}
// otherwise just pass the original response on
return response;
}
}
问题是,调用response.body.string()会消耗ResponseBody由于它是一次性的值作为Okhttp文档状态。
The issue is that calling response.body.string() will consume the ResponseBody due to it being a one-shot value as the Okhttp docs state.
这意味着,响应于code将不再容器时,它被传递给改型体的端返回。有没有办法,我可以消耗掉体内的同时仍与响应返回任何方式?
This means that the Response returned at the end of the code will no longer container the body when it is passed off to retrofit. Is there any way that I can consume the body while still returning it with the response?
谢谢!
推荐答案
我通过创建一个新的应答实现这个<一个href=\"http://square.github.io/okhttp/javadoc/com/squareup/okhttp/Response.Builder.html\">Response.Builder.我可以使用 responseBodyString
我的检查;然后我返回 newResponse
,这是因为我消耗身体。
I accomplished this by creating a new response using the Response.Builder. I am able to use responseBodyString
for my checks; then I return newResponse
, which is given the body that I consumed.
Request request = chain.request();
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
String responseBodyString = response.body().string();
Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();
...
return newResponse;
这篇关于从Okhttp消费单次ResponseBody导致与改造问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!