4

Is there a nice way to implement "blocking" request interceptor?

The main idea is that all requests should be intercepted and added additional header - token.

If token does not exist yet it should be retrieved first, then added to that request and cached for future used. token is retrieved via API call.

I've tried to do synchronous request, but, that produces android.os.NetworkOnMainThreadException. And implementing with in_progress flags it doesn't look nice.

Martynas Jurkus
  • 9,231
  • 13
  • 59
  • 101

3 Answers3

2

You can already do the 'intercept' part of this using RequestInterceptor. Just use RestAdapter.Builder.setRequestInterceptor().

It's a better idea to retrieve the token from the API outside the RequestInterceptor though, as it's not meant to do that. After that first call, you can just add the token anywhere you want in your requests inside RequestInterceptor.intercept().

Something like this:

Builder builder = new RestAdapter.Builder()
//Set Endpoint URL, Retrofit class... etc
.setRequestInterceptor(new RequestInterceptor() {
       @Override
       public void intercept(RequestFacade request) {
           String authToken = getAuthToken(); //Not included here, retrieve the token.
           request.addHeader("Authorization", "Bearer " + authToken);
       }
);
Hassan Ibraheem
  • 2,329
  • 1
  • 17
  • 23
  • Yeah, I was looking for a solution so that no request could be executed unless token is fetched. And it seemed like it's a good idea to delegate this job for this interceptor. – Martynas Jurkus May 03 '14 at 07:02
  • 1
    I get my token after my first request (Successful log in) how would I go about fetching that token an saving it into a variable? – frankelot May 27 '14 at 15:27
1

Well, you have already implemented your 'blocking' interceptor, your problem is android doesn't let you block the main thread with network calls.

You should probably wrap your retrofit calls in a service class that calls, asynchronously, to your getToken method, and makes the 'main' request only if and when that first one completes succesfully.

ivagarz
  • 2,434
  • 22
  • 22
1

As of OkHTTP 2.2, you can now add interceptors that run on the network thread:

https://github.com/square/okhttp/wiki/Interceptors

An example interceptor for adding an auth token might be like this;

public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    // Get your auth token by going out over the network.. 

    // add authorization header, defaulting to the original request.
    Request authedRequest = request;
    if (!TextUtils.isEmpty(authToken)) {
        authedRequest = request.newBuilder().addHeader("Auth", authToken).build();
    }

    return chain.proceed(authedRequest);
}
Matthew Runo
  • 1,387
  • 3
  • 20
  • 43