Retrofit介紹:
Retrofit和okHttp師出同門,也是Square的開源庫,它是一個類型安全的網絡請求庫,Retrofit簡化了網絡請求流程,基於OkHtttp做了封裝,解耦的更徹底:比方說通過注解來配置請求參數,通過工廠來生成CallAdapter,Converter,你可以使用不同的請求適配器(CallAdapter), 比方說RxJava,Java8, Guava。你可以使用不同的反序列化工具(Converter),比方說json, protobuff, xml, moshi等等。
- 官網 http://square.github.io/retrofit/
- github https://github.com/square/retrofit
Retrofit+OkHttpClient使用:
1.)在build.gradle中添加如下配置
compile 'com.squareup.retrofit2:retrofit:2.1.0'
2.)初始化Retrofit
retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(FastJsonConverterFactory.create()) .client(mOkHttpClient) .build();
3.)初始化OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS)//設置超時時間 .readTimeout(10, TimeUnit.SECONDS)//設置讀取超時時間 .writeTimeout(10, TimeUnit.SECONDS);//設置寫入超時時間 int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize); builder.cache(cache); builder.addInterceptor(interceptor); mOkHttpClient = builder.build();
關於okHttp的攔截器、Cache-Control等這里就不再做解說了
4.)關於ConverterFactory
對於okHttpClient的初始化我們都已經很熟悉了,對ConverterFactory初次接觸多少有點陌生,其實這個就是用來統一解析ResponseBody返回數據的。
常見的ConverterFactory
- Gson:
com.squareup.retrofit2:converter-gson
- Jackson:
com.squareup.retrofit2:converter-jackson
- Moshi:
com.squareup.retrofit2:converter-moshi
- Protobuf:
com.squareup.retrofit2:converter-protobuf
- Wire:
com.squareup.retrofit2:converter-wire
- Simple XML:
com.squareup.retrofit2:converter-simplexml
- Scalars (primitives, boxed, and String):
com.squareup.retrofit2:converter-scalars
由於項目中使用的是FastJson,所以只能自己自定義ConverterFactory,不過國內已經有大神對此作了封裝(http://www.tuicool.com/articles/j6rmyi7)。
- FastJson compile 'org.ligboy.retrofit2:converter-fastjson-android:2.0.2'
5.)定義接口 get 請求
1.get請求 不帶任何參數
public interface IApi { @GET("users")//不帶參數get請求 Call<List<User>> getUsers(); }
2.get請求 動態路徑 @Path使用
public interface IApi { @GET("users/{groupId}")//動態路徑get請求 Call<List<User>> getUsers(@Path("userId") String userId); }
3.get請求 拼接參數 @Query使用
public interface IApi { @GET("users/{groupId}") Call<List<User>> getUsers(@Path("userId") String userId, @Query("age")int age); }
3.get請求 拼接參數 @QueryMap使用
public interface IApi { @GET("users/{groupId}") Call<List<User>> getUsers(@Path("userId") String userId, @QueryMap HashMap<String, String> paramsMap); }
6.)定義接口 post請求
1.post請求 @body使用
public interface IApi { @POST("add")//直接把對象通過ConverterFactory轉化成對應的參數 Call<List<User>> addUser(@Body User user); }
2.post請求 @FormUrlEncoded,@Field使用
public interface IApi { @POST("login") @FormUrlEncoded//讀參數進行urlEncoded Call<User> login(@Field("userId") String username, @Field("password") String password); }
3.post請求 @FormUrlEncoded,@FieldMap使用
public interface IApi { @POST("login") @FormUrlEncoded//讀參數進行urlEncoded Call<User> login(@FieldMap HashMap<String, String> paramsMap); }
4.post請求 @Multipart,@Part使用
public interface IApi { @Multipart @POST("login") Call<User> login(@Part("userId") String userId, @Part("password") String password); }
7.)Cache-Control緩存控制
public interface IApi { @Headers("Cache-Control: max-age=640000") @GET("users")//不帶參數get請求 Call<List<User>> getUsers(); }
8.)請求使用
1.返回IApi
/** * 初始化Api */ private void initIApi() { iApi = retrofit.create(IApi.class); } /** * 返回Api */ public static IApi api() { return api.iApi; }
2.發送請求
Call<String> call = Api.api().login(userId,password); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { Log.e("", "response---->" + response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { Log.e("", "response----失敗"); } });
Retrofit+RxJava使用:
上面介紹了Retrofit 與OkHttp的結合,下面介紹一下Retrofit與RxJava的結合,RxJava作為當前的開源庫的網紅之一,Retrofit理所當然也提供了對其的支持,RxJava的強大之處強大的異步處理能力,Retrofit與RxJava的結合勢必提高開發效率以及運行性能。
1.)在原來的基礎上添加以下依賴
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1' // Retrofit的rx解析庫 compile 'io.reactivex:rxandroid:1.2.0' compile 'io.reactivex:rxjava:1.1.5'
2.)創建retrofit對象實例時,通過addCallAdapterFactory來添加對RxJava的支持
/** * 初始化Retrofit */ private void initRetrofit() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(FastJsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(mOkHttpClient) .build(); }
3.)定義請求接口
public interface IApi { @POST("system/login") Observable<String> systemLogin(@Body String userId, @Body String password);
}
4.)調用發送請求
Api.api().systemLogin(userId,password) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String result) { } });
總結:
這里簡單介紹了Retrofit與Okhttp、RxJava的結合使用。
https://www.cnblogs.com/whoislcj/p/5539239.html