Retrofit2 Deserialize Response Body Even If Response Is Not 200
Solution 1:
Retrofit is doing the serialization part by delegating it to the Converter, you you can add a specific one to the builder by using builder.addConverterFactory(GsonConverterFactory.create())
and there is already many written Retrofit Converters, you can find most of them here.
so if you want to control this process of deserialization, you can write your custom converter, something like this
publicclassUnwrapConverterFactoryextendsConverter.Factory {
privateGsonConverterFactory factory;
publicUnwrapConverterFactory(GsonConverterFactory factory) {
this.factory = factory;
}
@OverridepublicConverter<ResponseBody, ?> responseBodyConverter(final Type type,
Annotation[] annotations, Retrofit retrofit) {
// e.g. WrappedResponse<Person>Type wrappedType = newParameterizedType() {
@OverridepublicType[] getActualTypeArguments() {
// -> WrappedResponse<type>returnnewType[] {type};
}
@OverridepublicTypegetOwnerType() {
returnnull;
}
@OverridepublicTypegetRawType() {
returnWrappedResponse.class;
}
};
Converter<ResponseBody, ?> gsonConverter = factory
.responseBodyConverter(wrappedType, annotations, retrofit);
returnnewWrappedResponseBodyConverter(gsonConverter);
}
}
then you use addConverterFactory()
again to tell Retrofit about the new converter.
I should mention that you can use multiple converters in Retrofit which is awesome, it simply check converters by order till find the proper one to use.
resources: writing custom Retrofit converter, using multiple converters
Solution 2:
You can do something like following in response directly...
LoginResponse errorResponse = gson.fromJson(response.errorBody().string(), LoginResponse.class);
...or using interceptor
addInterceptor(getMyErrorResponseInterceptor())
protected Interceptor getMyErrorResponseInterceptor() {
returnnewInterceptor() {
@Overridepublic Response intercept(Chain chain)throws IOException {
Requestrequest= chain.request();
Responseresponse= chain.proceed(request);
if (response.code() >= 400) {
// handle error
}
return response;
}
};
}
Post a Comment for "Retrofit2 Deserialize Response Body Even If Response Is Not 200"