阻断请求拦截与改造? [英] Blocking request interceptor with Retrofit?

查看:511
本文介绍了阻断请求拦截与改造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有实行堵的好办法请求拦截?

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.

如果标记不存在但它应该首先检索,然后添加到该请求,并缓存使用的未来。 标记通过调用API进行检索。

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.

我试图做同步的请求,但是,产生 android.os.NetworkOnMainThreadException 。并与 IN_PROGRESS 标记实现它并不好看。

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

推荐答案

您已经可以做到这一点使用的 RequestInterceptor 。只需使用 RestAdapter.Builder.setRequestInterceptor()

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

这是一个更好的主意,虽然检索来自RequestInterceptor外部API令牌,因为它并不意味着这样做。首先调用之后,你可以添加你想要的任何地方标记在您的要求在 RequestInterceptor.intercept()

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().

事情是这样的:

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

这篇关于阻断请求拦截与改造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆