Blocking request interceptor with Retrofit?

感情迁移 提交于 2019-12-13 14:27:10

问题


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.


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/22016657/blocking-request-interceptor-with-retrofit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!