Android中Retrofit+OkHttp進(jìn)行HTTP網(wǎng)絡(luò)編程的使用指南
Retrofit介紹:
Retrofit(GitHub主頁(yè)https://github.com/square/okhttp)和OkHttp師出同門(mén),也是Square的開(kāi)源庫(kù),它是一個(gè)類(lèi)型安全的網(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è)置寫(xiě)入超時(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ù)的。
常見(jiàn)的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)引入依賴(lài):
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è)專(zhuān)門(mén)設(shè)計(jì)用于當(dāng)驗(yàn)證出現(xiàn)錯(cuò)誤的時(shí)候,進(jìn)行詢(xú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)文章
利用libmp3lame實(shí)現(xiàn)在Android上錄音MP3文件示例
本篇文章主要介紹了利用Lame庫(kù)實(shí)現(xiàn)在Android上錄音MP3文件示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-03-03
Android編程開(kāi)發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載
這篇文章主要介紹了Android編程開(kāi)發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載,總結(jié)了前面關(guān)于Java多線程下載的技巧,實(shí)例分析了Android實(shí)現(xiàn)帶百分比和進(jìn)度條的多線程下載技巧,需要的朋友可以參考下2015-12-12
android studio 一直卡在Gradle:Build Running的幾種解決辦法
這篇文章主要介紹了android studio 一直卡在Gradle:Build Running的解決辦法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-10-10
Android中自定義view實(shí)現(xiàn)側(cè)滑效果
這篇文章主要介紹了Android中自定義view實(shí)現(xiàn)側(cè)滑效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11
android實(shí)現(xiàn)搜索功能并將搜索結(jié)果保存到SQLite中(實(shí)例代碼)
這篇文章主要介紹了android實(shí)現(xiàn)搜索功能并將搜索結(jié)果保存到SQLite中,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04
AndroidStudio實(shí)現(xiàn)微信界面設(shè)計(jì)
這篇文章帶你通過(guò)Androidstudio來(lái)實(shí)現(xiàn)微信的基礎(chǔ)界面,微信的界面主要包含了主頁(yè)、通訊錄、發(fā)現(xiàn)以及我的賬號(hào)功能區(qū),下文包含了整個(gè)開(kāi)發(fā)過(guò)程,以及解決該問(wèn)題的過(guò)程及思路并提供了源碼2021-10-10
Android?EventBus粘性事件實(shí)現(xiàn)機(jī)制探究
最近項(xiàng)目做組件化,需要進(jìn)行組件化的通信,有時(shí)候可能會(huì)出現(xiàn)異步的情況,事件接收方還沒(méi)準(zhǔn)備好事件就已經(jīng)發(fā)送過(guò)來(lái)了,這時(shí)候想到了EventBus的粘性事件,這篇文章主要給大家介紹了關(guān)于Android?EventBus粘性事件實(shí)現(xiàn)機(jī)制的相關(guān)資料,需要的朋友可以參考下2022-05-05
最新評(píng)論
大家感興趣的內(nèi)容
- 1一看就懂的Android APP開(kāi)發(fā)入門(mén)教程
- 2微信公眾平臺(tái)開(kāi)發(fā)入門(mén)教程(圖文詳解)
- 3Android基礎(chǔ)之使用Fragment控制切換多個(gè)頁(yè)面
- 4六款值得推薦的android(安卓)開(kāi)源框架簡(jiǎn)介
- 5android TextView設(shè)置中文字體加粗實(shí)現(xiàn)方法
- 6Android應(yīng)用開(kāi)發(fā)SharedPreferences存儲(chǔ)
- 7Android 動(dòng)畫(huà)之TranslateAnimation應(yīng)
- 8android壓力測(cè)試命令monkey詳解
- 9Android按鈕單擊事件的四種常用寫(xiě)法總結(jié)
- 10android調(diào)試工具DDMS的使用詳解
最近更新的內(nèi)容
- Android線程實(shí)現(xiàn)圖片輪播
- 如何安裝adb工具及常用的adb命令
- android中的AIDL進(jìn)程間通信示例
- Android開(kāi)發(fā)工程中集成mob短信驗(yàn)證碼功能的方法
- 多面分析HarmonyOS與Android的特點(diǎn)
- Android實(shí)現(xiàn)畫(huà)板、寫(xiě)字板功能(附源碼下載)
- Android實(shí)現(xiàn)為GridView添加邊框效果
- Android FaceDetector實(shí)現(xiàn)人臉檢測(cè)功能
- Android Studio自動(dòng)生成UML關(guān)系圖的方法步驟
- Android中RecyclerView實(shí)現(xiàn)多級(jí)折疊列表效果(二)

