首页
登录 | 注册

Retrofit2.0封装 加header头部 加拦截器

public class RxRetrofitUtil {
    private static final String LOGIN="https://www.zhaoapi.cn/";
    private static volatile RxRetrofitUtil rxRetrofitUtil;
    private static BlogService service;
    private static RxRetrofitUtil getInstance(){
        if (rxRetrofitUtil == null) {
            synchronized (RxRetrofitUtil.class){
                if (rxRetrofitUtil == null) {
                    rxRetrofitUtil = new RxRetrofitUtil();
                }
            }
        }
        return rxRetrofitUtil;
    }
    public static BlogService doGet(){
        if (service == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.connectTimeout(3000, TimeUnit.SECONDS);
            builder.readTimeout(3000, TimeUnit.SECONDS);
            builder.writeTimeout(3000, TimeUnit.SECONDS);
            builder.addInterceptor(new HttpLoggingInterceptor());
            builder.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    .url()
                    .newBuilder()
                    .addQueryParameter("source", "android")
                    .build();
                    Request build = request.newBuilder()
                            .url(httpUrl)
                            .method(request.method(), request.body())
                            .build();
                    return chain.proceed(build);
                }
            });
            Retrofit build = new Retrofit.Builder()
                    .baseUrl(LOGIN)
                    .client(builder.build())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            service = build.create(BlogService.class);
        }
        return service;
    }
}


2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.008 s.
京ICP备10005923号