經過上面的學習,咱們不難發現單純使用okHttp來做爲網絡庫仍是多多少少有那麼一點點不太方便,並且還需本身來管理接口,對於接口的使用的是哪一種請求方式也不能一目瞭然,出於這個目的接下來學習一下Retrofit+Okhttp的搭配使用。html
okHttp相關文章地址:java
Retrofit和okHttp師出同門,也是Square的開源庫,它是一個類型安全的網絡請求庫,Retrofit簡化了網絡請求流程,基於OkHtttp作了封裝,解耦的更完全:比方說經過註解來配置請求參數,經過工廠來生成CallAdapter,Converter,你可使用不一樣的請求適配器(CallAdapter), 比方說RxJava,Java8, Guava。你可使用不一樣的反序列化工具(Converter),比方說json, protobuff, xml, moshi等等。react
compile 'com.squareup.retrofit2:retrofit:2.1.0'
retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(FastJsonConverterFactory.create()) .client(mOkHttpClient) .build();
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等這裏就再也不作解說了android
對於okHttpClient的初始化咱們都已經很熟悉了,對ConverterFactory初次接觸多少有點陌生,其實這個就是用來統一解析ResponseBody返回數據的。git
常見的ConverterFactorygithub
com.squareup.retrofit2:converter-gson
com.squareup.retrofit2:converter-jackson
com.squareup.retrofit2:converter-moshi
com.squareup.retrofit2:converter-protobuf
com.squareup.retrofit2:converter-wire
com.squareup.retrofit2:converter-simplexml
com.squareup.retrofit2:converter-scalars
因爲項目中使用的是FastJson,因此只能本身自定義ConverterFactory,不過國內已經有大神對此做了封裝(http://www.tuicool.com/articles/j6rmyi7)。json
1.get請求 不帶任何參數api
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); }
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); }
public interface IApi { @Headers("Cache-Control: max-age=640000") @GET("users")//不帶參數get請求 Call<List<User>> getUsers(); }
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 與OkHttp的結合,下面介紹一下Retrofit與RxJava的結合,RxJava做爲當前的開源庫的網紅之一,Retrofit理所固然也提供了對其的支持,RxJava的強大之處強大的異步處理能力,Retrofit與RxJava的結合勢必提升開發效率以及運行性能。
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'
/** * 初始化Retrofit */ private void initRetrofit() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(FastJsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(mOkHttpClient) .build(); }
public interface IApi { @POST("system/login") Observable<String> systemLogin(@Body String userId, @Body String password);
}
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的結合使用。