retrofit封装网络请求工具有bug请教

小蛇丸快跑 发布于 2017/03/13 10:39
阅读 161
收藏 0
  1.   首先感谢看帖的人。

    问题,公司的api需要token验证才能访问,然后就是获取token需要加上body参数(这个 ),目前问题来了,我写了一个工具类,通过okhttp拦截器来插入token参数,并且拦截器里面通过retrofit来请求token。每次打开app请求网络的时候,token每次都会被请求(我只想让他请求一次,如果失效了,再重新请求),但是请求接口会先失败一次,后面都会成功。我稍后贴下代码,请帮忙分析一下啊。

/**
*这个是工具类
*/
public class RetrofitUtil {
    TokenInterceptor interceptor;

    OkHttpClient client;

    public RetrofitUtil() {
        if (interceptor == null) {
            interceptor = new TokenInterceptor(TokenUtil.getToken());
        }
        if (client == null) {
            client = new OkHttpClient()
                    .newBuilder()
                    .addInterceptor(interceptor)
                    .build();
        }
    }


    public Retrofit getRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)//注意此处,设置服务器的地址
                .addConverterFactory(GsonConverterFactory.create())//用于Json数据的转换,非必须
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//用于返回Rxjava调用,非必须
                .build();
    }
}
//token url
public interface API {
    @FormUrlEncoded
    @POST("/token")
    Observable<TokenBean> getToken(@FieldMap Map<String, String> body);
}
//我用这个来请求token,
public class TokenUtil {
    private static TokenBean tokenBean;

    public static String getToken() {
        API api = new Retrofit.Builder()
                .baseUrl(BASE_URL.BASE_URL_TOKEN)//注意此处,设置服务器的地址
                .addConverterFactory(GsonConverterFactory.create())//用于Json数据的转换,非必须
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//用于返回Rxjava调用,非必须
                .build()
                .create(API.class);
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "client_credentials");
        map.put("client_id", "------");
        map.put("client_secret", "------");
        Observable<TokenBean> observable = api.getToken(map);
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<TokenBean>() {
                    @Override
                    public void onCompleted() {
                        Toast.makeText(AppContext.context(), "加载完成1", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Toast.makeText(AppContext.context(), "加载失败1", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(TokenBean tokenBean) {
                        Log.d("-----", "onNext: " + tokenBean.toString());
                        TokenUtil.tokenBean = tokenBean;
                    }
                });
        return tokenBean == null ? "" : tokenBean.getToken_type() + " " + tokenBean.getAccess_token();
    }
}

 

//okhttp3的拦截器,用来插入token参数
public class TokenInterceptor implements Interceptor {

    private static final String USER_TOKEN = "Authorization";
    private final String token;

    public TokenInterceptor(String token) {
        this.token = token;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        if (token == null || originalRequest.header(USER_TOKEN) != null) {
            Log.d("-----", "intercept:run 1 ");
            return chain.proceed(originalRequest);
        }
        Request request = originalRequest.newBuilder()
                .header(USER_TOKEN, token)
                .build();
        Log.d("-----", "intercept:run 2");
        return chain.proceed(request);
    }
}

 

//实现tokenAPI接口的实现类。
public class ServiceManager implements ApiService {
    public static ApiService getService(Class clazz) {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL.BASE_URL_TOKEN)//注意此处,设置服务器的地址
                .addConverterFactory(GsonConverterFactory.create())//用于Json数据的转换,非必须
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//用于返回Rxjava调用,非必须
                .build()
                .create(ApiService.class);
    }

    @Override
    public Observable<TokenBean> getToken(@FieldMap Map<String, String> body) {
        return getService(this.getClass()).getToken(body);
    }
}
加载中
返回顶部
顶部