Retrofit+RXJava+OkHttp

添加依赖:
//rxjava相关依赖
compile 'io.reactivex:rxjava:1.2.1'
compile 'io.reactivex:rxandroid:1.2.1'

// retrofit相关依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

// okhttp相关依赖
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

import retrofit2.converter.gson.GsonConverterFactory;

import okhttp3.logging.HttpLoggingInterceptor;

/**
 *
 * 网络请求工具类
 */

public class Retrofit_Utils {
    //双重检验锁
    private volatile static Retrofit_Utils util=null;
    private Retrofit_Utils(){

    }
    public static Retrofit_Utils getmInstance(){
        if (util==null){
            synchronized (Retrofit_Utils.class){
                if (util==null){
                    util=new Retrofit_Utils();
                }
            }
        }
        return util;
    }

        public GetRequest_Interface getRequestInterface(String str){


       //okHttp拦截器+日志拦截器
        OkHttpClient builder = new OkHttpClient.Builder()
                .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
                .addInterceptor(new MyInter())//拦截器
                .build();

            //创建Retrofit实例
            retrofit2.Retrofit retrofit=new retrofit2.Retrofit.Builder()
                    .baseUrl(str)//设置网路请求URL
                    .client(builder)//设置okHttp拦截器
                    .addConverterFactory(GsonConverterFactory.create())//设置数据解析器
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//支持RXjava平台
                    .build();

            GetRequest_Interface anInterface = retrofit.create(GetRequest_Interface.class);

            return anInterface;
        }

    //拦截器
    public class MyInter implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //获取到request
            Request request = chain.request();
            HttpUrl httpUrl = request
                    .url()
                    .newBuilder()
                    .addQueryParameter("source", "android")
                    .addQueryParameter("appVersion","101")
                    .build();
            Request requestNew = request
                    .newBuilder()
                    .url(httpUrl)
                    .build();
            return chain.proceed(requestNew);

        }
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值