Interceptor request blocking with retrofit?

Is there a good way to implement a “blocking” interceptor request?

The basic idea is that all requests should be intercepted and additional headers added token.

If tokenit does not already exist, it must first be extracted, then added to this request and cached for future use. tokenretrieved through an API call.

I tried to execute a synchronous request, but it creates android.os.NetworkOnMainThreadException. And the implementation with flags in_progressdoes not look very good.

+3
source share
3 answers

"", RequestInterceptor. RestAdapter.Builder.setRequestInterceptor().

API RequestInterceptor, . RequestInterceptor.intercept().

- :

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);
       }
);
+2

, "" , .

, , , getToken, , .

+1

Starting with OkHTTP 2.2, now you can add sniffers that execute on the network stream:

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

An example interceptor for adding an authentication token might look 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);
}
+1
source

All Articles