简体   繁体   English

如何在拦截中更改响应主体(使用改造 2)

[英]How to change response body in intercept (Using retrofit 2)

I read thousand of answers and try to a lot of way but doesn't work.我阅读了数千个答案并尝试了很多方法但不起作用。 I really need to change response body when get "401".获得“401”时,我真的需要更改响应正文。 Because server response is different from other general response when unauthorized.因为服务器响应不同于其他未经授权的一般响应。

I'm using retrofit 2. To catch response i'm using Interceptor:我正在使用改造 2。为了捕捉响应,我正在使用拦截器:

                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        .header("authorization", getAccessToken(context));
                Request request = requestBuilder.build();
                Response response= chain.proceed(request);
                if (response.code()==401) {
                    MediaType contentType = response.body().contentType();
                    ResponseBody body = ResponseBody.create(contentType, CommonFunctions.getUnAuthorizedJson(context).toString());
                    return response.newBuilder().body(body).build();
                }else{
                    return response;
                }

But still body doesn't change on client.enque method.但是在 client.enque 方法上 body 仍然没有改变。

You can change body in this way, but Retrofit will eventually see 401 and throw HttpException with standart message, what can be misleading您可以通过这种方式更改正文,但是 Retrofit 最终会看到 401 并抛出带有标准消息的 HttpException,这可能会产生什么误导

check that you get your body right:检查你的身体是否正确:


val errorConverter: Converter<ResponseBody, ErrorResponse> =
        retrofit.responseBodyConverter(
            ErrorResponse::class.java,
            emptyArray()
        )

val errorResponse = httpException
            .response()
            ?.errorBody()
            ?.let (errorConverter::convert)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM