Interceptor blocking queries with Retrofit?
source link: https://www.codesd.com/item/interceptor-blocking-queries-with-retrofit.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Interceptor blocking queries with Retrofit?
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.
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);
}
);
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK