Android请求时候添加共同的参数

Android在联网请求时候需要添加共同的参数比如Token,如果每次都在请求时候添加的请求参数中会很麻烦,可以添加到请求头中,每次联网操作就不需要添加了,我联网操作使用的是Retrofit,忘记是看到的哪位大神的博客了,Retrofit的封装是借鉴的别人的。

RetrofitManager.java

public class RetrofitManager {
    private static RetrofitManager mRetrofitManager;
    private Retrofit mRetrofit;
    private static final String TAG = "RetrofitManager";
    private RetrofitManager(){
        initRetrofit();
    }

    public static RetrofitManager getInstance(){
        if (mRetrofitManager == null){
            mRetrofitManager = new RetrofitManager();
        }
        return mRetrofitManager;
    }


    private void initRetrofit() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new TokenInterceptor());//添加Token控制拦截器
        File cacheFile = new File(context.getCacheDir()+"");
        Cache cache = new Cache(cacheFile,Constant.CACHE_SIZE);
        builder.cache(cache);
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        OkHttpClient client = builder.build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }

    public <T> T createReq(Class<T> reqServer){
        return mRetrofit.create(reqServer);
    }


    

    public class TokenInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder().addHeader("Cookie", "wf_token=" + SPUtils.getToken()).build();
            Response response = chain.proceed(request);
            return response;
        }
    }



}

通过抓包工具抓包,获取数据如下:


阅读更多
个人分类: android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭