標籤:
前言:
通過上面的學習,我們不難發現單純使用okHttp來作為網路程式庫還是多多少收有那麼一點點不太方便,而且還需自己來管理介面,對於介面的使用的是哪種請求方式也不能一目瞭然,出於這個目的接下來學習一下Retrofit+Okhttp的搭配使用。
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使用:1.)在build.gradle中添加如下配置
compile ‘com.squareup.retrofit2:retrofit:2.0.2‘
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‘
重點看下Factory類的實現
abstract class Factory { public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return null; } public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { return null; } public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return null; } }
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()); request_tv.setText(response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { Log.e("", "response----失敗"); } });
Android探索之基於okHttp打造自己的網路請求<Retrofit+Okhttp>(五)