添加依赖:
//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){
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);
}
}
}