Android中Retrofit+OkHttp進行HTTP網(wǎng)絡(luò)編程的使用指南
Retrofit介紹:
Retrofit(GitHub主頁https://github.com/square/okhttp)和OkHttp師出同門,也是Square的開源庫,它是一個類型安全的網(wǎng)絡(luò)請求庫,Retrofit簡化了網(wǎng)絡(luò)請求流程,基于OkHtttp做了封裝,解耦的更徹底:比方說通過注解來配置請求參數(shù),通過工廠來生成CallAdapter,Converter,你可以使用不同的請求適配器(CallAdapter), 比方說RxJava,Java8, Guava。你可以使用不同的反序列化工具(Converter),比方說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è)置超時時間
.readTimeout(10, TimeUnit.SECONDS)//設(shè)置讀取超時時間
.writeTimeout(10, TimeUnit.SECONDS);//設(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等這里就不再做解說了4.關(guān)于ConverterFactory
對于okHttpClient的初始化我們都已經(jīng)很熟悉了,對ConverterFactory初次接觸多少有點陌生,其實這個就是用來統(tǒng)一解析ResponseBody返回數(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
由于項目中使用的是FastJson,所以只能自己自定義ConverterFactory。
5.定義接口 get 請求
(1)get請求 不帶任何參數(shù)
public interface IApi {
@GET("users")//不帶參數(shù)get請求
Call<List<User>> getUsers();
}
(2)get請求 動態(tài)路徑 @Path使用
public interface IApi {
@GET("users/{groupId}")//動態(tài)路徑get請求
Call<List<User>> getUsers(@Path("userId") String userId);
}
(3)get請求 拼接參數(shù) @Query使用
public interface IApi {
@GET("users/{groupId}")
Call<List<User>> getUsers(@Path("userId") String userId, @Query("age")int age);
}
6.定義接口 post請求
(1)post請求 @body使用
public interface IApi {
@POST("add")//直接把對象通過ConverterFactory轉(zhuǎn)化成對應(yīng)的參數(shù)
Call<List<User>> addUser(@Body User user);
}
(2)post請求 @FormUrlEncoded,@Field使用
public interface IApi {
@POST("login")
@FormUrlEncoded//讀參數(shù)進行urlEncoded
Call<User> login(@Field("userId") String username, @Field("password") String password);
}
(3)post請求 @FormUrlEncoded,@FieldMap使用
public interface IApi {
@POST("login")
@FormUrlEncoded//讀參數(shù)進行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")//不帶參數(shù)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)發(fā)送請求
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.攔截器配置
攔截器配置要點引入依賴:
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)錯誤進行重新連接。
(3)connectTimeout 設(shè)置超時時間
(4)addNetworkInterceptor 讓所有網(wǎng)絡(luò)請求都附上你的攔截器,我這里設(shè)置了一個 token 攔截器,就是在所有網(wǎng)絡(luò)請求的 header 加上 token 參數(shù),下面會稍微講一下這個內(nèi)容。
讓所有網(wǎng)絡(luò)請求都附上你的攔截器:
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,如果你的不是這個,可以修改。
(3)如果你需要在遇到諸如 401 Not Authorised 的時候進行刷新 token,可以使用 Authenticator,這是一個專門設(shè)計用于當(dāng)驗證出現(xià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 對象
(3)addCallAdapterFactory 增加 RxJava 適配器
(4)addConverterFactory 增加 Gson 轉(zhuǎn)換器
- Retrofit之OKHttpCall源碼分析
- Okhttp、Retrofit進度獲取的方法(一行代碼搞定)
- Android 封裝Okhttp+Retrofit+RxJava,外加攔截器實例
- okhttp3.4.1+retrofit2.1.0實現(xiàn)離線緩存的示例
- OKHttp3(支持Retrofit)的網(wǎng)絡(luò)數(shù)據(jù)緩存Interceptor攔截器的實現(xiàn)
- RxJava+Retrofit+OkHttp實現(xiàn)多文件下載之?dāng)帱c續(xù)傳
- RxJava+Retrofit+OkHttp實現(xiàn)文件上傳
- 深入淺出RxJava+Retrofit+OkHttp網(wǎng)絡(luò)請求
- 淺談RxJava+Retrofit+OkHttp 封裝使用
- Retrofit和OkHttp如何實現(xiàn)Android網(wǎng)絡(luò)緩存
相關(guān)文章
Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫的方法
這篇文章主要為大家詳細介紹了Android批量插入數(shù)據(jù)到SQLite數(shù)據(jù)庫的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
Android開發(fā)筆記之如何正確獲取WebView的網(wǎng)頁Title
獲取h5頁面的攜帶的title中是很簡單的,下面這篇文章主要給大家介紹了關(guān)于Android開發(fā)筆記之如何正確獲取WebView的網(wǎng)頁Title的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友們下面來一起看看吧2018-09-09
Android中findViewById返回為空null的快速解決辦法
這篇文章主要介紹了Android中findViewById返回為空null的快速解決辦法的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-06-06
android實現(xiàn)RecyclerView列表單選功能
這篇文章主要為大家詳細介紹了android實現(xiàn)RecyclerView列表單選功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Android 自定義精美界面包含選項菜單 上下文菜單及監(jiān)聽詳解流程
這篇文章主要介紹了一個Android實例小項目,它包含了選項菜單、上下文菜單及其對應(yīng)的監(jiān)聽事件,它很小,但這部分功能在Android開發(fā)中很常見,需要的朋友來看看吧2021-11-11
Android Broadcast 和 BroadcastReceiver的權(quán)限限制方式
這篇文章主要介紹了Android Broadcast 和 BroadcastReceiver的權(quán)限限制方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03

