Corneliu
Corneliu

Reputation: 451

Retrofit intercept response

I have the following code for a ws request :

RestAdapter mRestAdapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_HOME_URL)
            .setRequestInterceptor(mRequestInterceptor)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();


    mInterfaceWs = mRestAdapter.create(InterfaceWs.class);

How can i intercept the response before it arrives in my model ? I wana replace some keys strings inside the response.

Inside my response i have some keys named : .type and #text and inside my model i can not set those names as fields

What can i do ? Please help me

compile 'com.squareup.retrofit:retrofit:1.7.0'



RequestInterceptor mRequestInterceptor = new RequestInterceptor()
    {
        @Override
        public void intercept(RequestFacade request)
        {
            request.addHeader("Accept","application/json");
        }
    };

Upvotes: 1

Views: 3316

Answers (2)

Corneliu
Corneliu

Reputation: 451

So... i managed to solve my problem without any intercetor.

For those who will have the same problem as i did :

public class Atribute
{
@SerializedName(".type")
public String type;

@SerializedName("#text")
public String text;

public String getType() { return type; }
public String getText() { return text; }
}

Upvotes: 2

Saurabh
Saurabh

Reputation: 1065

You can use OKHttp Network Interceptors to intercept the response and modify it. For this you would need to setup a custom OkHTTP client to use with retrofit.

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                com.squareup.okhttp.Response response = chain.proceed(chain.request());
                //GET The response body and modify it before returning
                return response;
            }
        });

Then set it up to use with retrofit.

RestAdapter mRestAdapter = new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setEndpoint(ROOT_HOME_URL)
            .setRequestInterceptor(mRequestInterceptor)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

You can read up more about network interceptors here

P.S: The link is for the latest version of OkHttp. The way you initialise network interceptors have changed in the latest version of OkHttp but the concept is the same. The code I gave should work with your old version (retrofit 1.7.0)

Upvotes: 0

Related Questions