Retrofit+Rxjava+ok+拦截器+RecyclerView+XRecyclerView
//依赖
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.facebook.fresco:fresco:0.14.1'
compile 'com.jcodecraeer:xrecyclerview:1.3.2'
compile 'com.android.support:recyclerview-v7:21.0.+'
compile 'com.squareup.okhttp3:okhttp:3.0.0'
compile 'com.squareup.okio:okio:1.5.0'
// 封装类
package greendao.bewei.com.lianxi;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitUtils {
private static RetrofitUtils retrofitUtils;
private RetrofitUtils(){
}
public static RetrofitUtils getInstance(){
if(retrofitUtils==null){
synchronized (RetrofitUtils.class){
if(retrofitUtils==null){
retrofitUtils=new RetrofitUtils();
}
}
}
return retrofitUtils;
}
private static Retrofit retrofit;
public static synchronized Retrofit getRetrofit(String url){
//日志拦截器
/* HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("xxx",message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);*/
//网络拦截器
LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
OkHttpClient okHttpClient=new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.connectTimeout(500, TimeUnit.SECONDS)
.readTimeout(500,TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.build();
if(retrofit==null){
retrofit=new Retrofit.Builder().baseUrl(url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
return retrofit;
}
public <T>T getApiService(String url,Class<T> cl){
Retrofit retrofit = getRetrofit(url);//得到retrofit
return retrofit.create(cl);//返回的就是网络接口对象
}
}
//拦截器
package test.bwie.com.mymusic.Model.OkHttp;
import android.os.Build;
import android.util.Log;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.logging.Logger;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* 网络拦截器
*/
public class LoggingInterceptor implements Interceptor {
private static final String UA = "User-Agent";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader(UA, makeUA())
.build();
return chain.proceed(request);
}
private String makeUA() {
String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;
return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;
}
}