Android中Retrofit+OkHttp進(jìn)行HTTP網(wǎng)絡(luò)編程的使用指南
Retrofit介紹:
Retrofit(GitHub主頁(yè)https://github.com/square/okhttp)和OkHttp師出同門,也是Square的開源庫(kù),它是一個(gè)類型安全的網(wǎng)絡(luò)請(qǐng)求庫(kù),Retrofit簡(jiǎn)化了網(wǎng)絡(luò)請(qǐng)求流程,基于OkHtttp做了封裝,解耦的更徹底:比方說(shuō)通過(guò)注解來(lái)配置請(qǐng)求參數(shù),通過(guò)工廠來(lái)生成CallAdapter,Converter,你可以使用不同的請(qǐng)求適配器(CallAdapter), 比方說(shuō)RxJava,Java8, Guava。你可以使用不同的反序列化工具(Converter),比方說(shuō)json, protobuff, xml, moshi等等。
官網(wǎng) 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)//設(shè)置超時(shí)時(shí)間 .readTimeout(10, TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間 .writeTimeout(10, TimeUnit.SECONDS);//設(shè)置寫入超時(shí)時(shí)間 int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize); builder.cache(cache); builder.addInterceptor(interceptor); mOkHttpClient = builder.build();關(guān)于okHttp的攔截器、Cache-Control等這里就不再做解說(shuō)了
4.關(guān)于ConverterFactory
對(duì)于okHttpClient的初始化我們都已經(jīng)很熟悉了,對(duì)ConverterFactory初次接觸多少有點(diǎn)陌生,其實(shí)這個(gè)就是用來(lái)統(tǒng)一解析ResponseBody返回?cái)?shù)據(jù)的。
常見的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
由于項(xiàng)目中使用的是FastJson,所以只能自己自定義ConverterFactory。
5.定義接口 get 請(qǐng)求
(1)get請(qǐng)求 不帶任何參數(shù)
public interface IApi { @GET("users")//不帶參數(shù)get請(qǐng)求 Call<List<User>> getUsers(); }
(2)get請(qǐng)求 動(dòng)態(tài)路徑 @Path使用
public interface IApi { @GET("users/{groupId}")//動(dòng)態(tài)路徑get請(qǐng)求 Call<List<User>> getUsers(@Path("userId") String userId); }
(3)get請(qǐng)求 拼接參數(shù) @Query使用
public interface IApi { @GET("users/{groupId}") Call<List<User>> getUsers(@Path("userId") String userId, @Query("age")int age); }
6.定義接口 post請(qǐng)求
(1)post請(qǐng)求 @body使用
public interface IApi { @POST("add")//直接把對(duì)象通過(guò)ConverterFactory轉(zhuǎn)化成對(duì)應(yīng)的參數(shù) Call<List<User>> addUser(@Body User user); }
(2)post請(qǐng)求 @FormUrlEncoded,@Field使用
public interface IApi { @POST("login") @FormUrlEncoded//讀參數(shù)進(jìn)行urlEncoded Call<User> login(@Field("userId") String username, @Field("password") String password); }
(3)post請(qǐng)求 @FormUrlEncoded,@FieldMap使用
public interface IApi { @POST("login") @FormUrlEncoded//讀參數(shù)進(jìn)行urlEncoded Call<User> login(@FieldMap HashMap<String, String> paramsMap); }
(4)post請(qǐng)求 @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")//不帶參數(shù)get請(qǐng)求 Call<List<User>> getUsers(); }
8.請(qǐng)求使用
(1)返回IApi
/** * 初始化Api */ private void initIApi() { iApi = retrofit.create(IApi.class); } /** * 返回Api */ public static IApi api() { return api.iApi; }
(2)發(fā)送請(qǐng)求
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----失敗"); } });
9.攔截器配置
攔截器配置要點(diǎn)引入依賴:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4' compile 'com.squareup.okhttp3:okhttp:3.0.1' compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .retryOnConnectionFailure(true) .connectTimeout(15, TimeUnit.SECONDS) .addNetworkInterceptor(mTokenInterceptor) .build();
(2)retryOnConnectionFailure 方法為設(shè)置出現(xiàn)錯(cuò)誤進(jìn)行重新連接。
(3)connectTimeout 設(shè)置超時(shí)時(shí)間
(4)addNetworkInterceptor 讓所有網(wǎng)絡(luò)請(qǐng)求都附上你的攔截器,我這里設(shè)置了一個(gè) token 攔截器,就是在所有網(wǎng)絡(luò)請(qǐng)求的 header 加上 token 參數(shù),下面會(huì)稍微講一下這個(gè)內(nèi)容。
讓所有網(wǎng)絡(luò)請(qǐng)求都附上你的攔截器:
Interceptor mTokenInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) { return chain.proceed(originalRequest); } Request authorised = originalRequest.newBuilder() .header("Authorization", Your.sToken) .build(); return chain.proceed(authorised); } };
(2)header 的 key 通常是 Authorization,如果你的不是這個(gè),可以修改。
(3)如果你需要在遇到諸如 401 Not Authorised 的時(shí)候進(jìn)行刷新 token,可以使用 Authenticator,這是一個(gè)專門設(shè)計(jì)用于當(dāng)驗(yàn)證出現(xiàn)錯(cuò)誤的時(shí)候,進(jìn)行詢問(wèn)獲取處理的攔截器:
Authenticator mAuthenticator = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { Your.sToken = service.refreshToken(); return response.request().newBuilder() .addHeader("Authorization", newAccessToken) .build(); } }
Retrofit retrofit = new Retrofit.Builder() .baseUrl(AppConfig.BASE_URL) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); service = retrofit.create(YourApi.class);
(2)client 即上面的 OkHttp3 對(duì)象
(3)addCallAdapterFactory 增加 RxJava 適配器
(4)addConverterFactory 增加 Gson 轉(zhuǎn)換器
- Retrofit之OKHttpCall源碼分析
- Okhttp、Retrofit進(jìn)度獲取的方法(一行代碼搞定)
- Android 封裝Okhttp+Retrofit+RxJava,外加攔截器實(shí)例
- okhttp3.4.1+retrofit2.1.0實(shí)現(xiàn)離線緩存的示例
- OKHttp3(支持Retrofit)的網(wǎng)絡(luò)數(shù)據(jù)緩存Interceptor攔截器的實(shí)現(xiàn)
- RxJava+Retrofit+OkHttp實(shí)現(xiàn)多文件下載之?dāng)帱c(diǎn)續(xù)傳
- RxJava+Retrofit+OkHttp實(shí)現(xiàn)文件上傳
- 深入淺出RxJava+Retrofit+OkHttp網(wǎng)絡(luò)請(qǐng)求
- 淺談RxJava+Retrofit+OkHttp 封裝使用
- Retrofit和OkHttp如何實(shí)現(xiàn)Android網(wǎng)絡(luò)緩存
相關(guān)文章
Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫(kù)的方法
這篇文章主要為大家詳細(xì)介紹了Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫(kù)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03Android開發(fā)筆記之如何正確獲取WebView的網(wǎng)頁(yè)Title
獲取h5頁(yè)面的攜帶的title中是很簡(jiǎn)單的,下面這篇文章主要給大家介紹了關(guān)于Android開發(fā)筆記之如何正確獲取WebView的網(wǎng)頁(yè)Title的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面來(lái)一起看看吧2018-09-09Android中findViewById返回為空null的快速解決辦法
這篇文章主要介紹了Android中findViewById返回為空null的快速解決辦法的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06android實(shí)現(xiàn)RecyclerView列表單選功能
這篇文章主要為大家詳細(xì)介紹了android實(shí)現(xiàn)RecyclerView列表單選功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07Android 自定義精美界面包含選項(xiàng)菜單 上下文菜單及監(jiān)聽詳解流程
這篇文章主要介紹了一個(gè)Android實(shí)例小項(xiàng)目,它包含了選項(xiàng)菜單、上下文菜單及其對(duì)應(yīng)的監(jiān)聽事件,它很小,但這部分功能在Android開發(fā)中很常見,需要的朋友來(lái)看看吧2021-11-11Android Broadcast 和 BroadcastReceiver的權(quán)限限制方式
這篇文章主要介紹了Android Broadcast 和 BroadcastReceiver的權(quán)限限制方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03