1、簡介java
Retrofit在OkHttp之上對網絡請求、數據結果作了封裝,是一款爲簡化網絡操做推出的框架。react
2、gradle依賴android
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'json
3、實現步驟緩存
1.建立REST API網絡
public interface HttpService {
@GET("/")
Call<TestEntity> getData();
}
2.配置Retrofit框架
private HttpService createHttpApi(){ Retrofit retrofit = new Retrofit .Builder() .baseUrl(base_url) .client(OkHttpSetting.mOkHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//設置RxJavaCallAdapter .addConverterFactory(GsonConverterFactory.create())//Gson數據轉換格式 .build(); return retrofit.create(HttpService.class); }
3.配置OkHttp異步
public class OkHttpSetting { private static final String TAG = OkHttpSetting.class.getSimpleName(); public static OkHttpClient mOkHttpClient = new OkHttpClient(); private static HttpLoggingInterceptor loggingBody; private static Interceptor interceptor;//攔截器,能夠攔截髮出的請求和返回的信息日誌 public OkHttpSetting(){ Log.i(TAG, "OkHttpSetting"); if(mOkHttpClient == null){ interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Log.i(TAG, "intercept"); Request request = chain.request(); Response response = chain.proceed(request); return response; } }; mOkHttpClient.interceptors().add(interceptor);//設置攔截器 mOkHttpClient.setConnectTimeout(60, TimeUnit.SECONDS); mOkHttpClient.setReadTimeout(60, TimeUnit.SECONDS); } } static { //設置http日誌緩存 if(loggingBody == null){ loggingBody = new HttpLoggingInterceptor(); loggingBody.setLevel(HttpLoggingInterceptor.Level.BODY); mOkHttpClient.networkInterceptors().add(loggingBody); } Interceptor trace = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); Log.i(TAG, "http日誌"); return response; } }; mOkHttpClient.interceptors().add(trace); Log.i(TAG, "setting"); } }
4.執行請求(同步:execute 異步:enqueue)ide
Call<TestEntity> call = createHttpApi().getData(); call.enqueue(new Callback<TestEntity>() {//異步執行 @Override public void onResponse(Response<TestEntity> response, Retrofit retrofit) { TestEntity entity = response.body(); int code = response.code(); Log.i(TAG, "onResponse"); } @Override public void onFailure(Throwable t) { Log.i(TAG, t.getMessage()); } });
4、版本對比(1.x和2.x)gradle
1.版本1.x沒有直接取消正在進行中任務的方法,而2.x能夠用cancle()方法取消。
2.版本1.x中包含GsonConverter而且在RestAdapter建立的時候被初始化,這樣會自動解析json數據。但在版本2.x中,須要本身插入一個Converter,不然只能接受字符串結果。依賴的包:
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
3.若是想接受json數據並解析,須要導入retrofit:converter-gson包,而後addConverterFactory(GsonConverterFactory.create())。
4.版本1.x中okhttp是可選的,在2.x中,okhttp是必須的,而且自動設置了依賴。
5.版本1.x中包含了RequestInterceptor,而在版本2.x中將這一部分移除,改成使用Okhttp中的Interceptor。
6.除了使用Call定義接口返回數據,版本2.x還提供了CallAdapter機制,其中最著名的是爲RxJava提供的CallAdapter,它可將接口返回數據做爲Observable。依賴的包以下:
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
compile 'io.reactivex:rxandroid:1.0.1'