前言
相信小伙伴們就算沒有用過retrofit也聽說過吧,retrofit是由Square公司出品的針對于Android和Java的類型安全的Http客戶端,其內部就是對okhttp進行的一個封裝,那么接下來,我就給大家帶來Retrofit在平時開發中的一些用法。
用法
1.在你的項目中的gradle中配置
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.1.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
這里說明一下,compile 'com.squareup.retrofit2:converter-gson:2.1.0'
主要是針對返回值做一個gson解析,一般都會加上,而compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0''
主要是配合rxjava使用,稍后會給大家帶來retrofit如何配合rxjava使用。
2.自定義一個interface并且在里面配置請求
public interface Service {
@FormUrlEncoded
@POST("user/login")
Call<LoginResponse> Login(@FieldMap Map<String, String> map);
現在看不懂沒關系,大家只要知道,@POST代表是一個post請求,后面的("user/login")表示請求地址,泛型代表的是你要的返回值,方法里面的參數代表請求要攜帶的參數,登錄一般都會要帳號密碼,所以這里寫的是一個Map集合。
3.開始做網絡請求
//拿到一個builder
Retrofit.Builder builder = new Retrofit.Builder();
//添加你的baseUrl,一般在開發中,baseUrl是固定的,大家可以定義一個常量
builder.baseUrl("www.baseurl.com/");
//添加Gson支持
builder.addConverterFactory(GsonConverterFactory.create());
//拿到一個retrofit對象
Retrofit retrofit = builder.build();
//傳入你之前定義的一個接口
Service service = retrofit.create(Service.class);
Map<String, String> map = new HashMap<>();
map.put("name","用戶名");
map.put("psw","密碼");
//調用接口中你自己定義的方法,并傳入參數,拿到一個call對象
Call<LoginResponse> call = service.Login(map);
//發送異步請求并添加回調,這里還有一個execute()是同步請求
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
//請求成功,拿到返回值
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
//請求失敗
}
});
到了這里,一個完整的網絡請求也就完成了,那么接下來給大家介紹介紹一些常用的注解。
4.常用注解介紹
@GET
get請求,分為不帶參數,一個參數,多個參數
- 不攜帶參數
@GET("user/login")
Call<LoginResponse> Login();
- 攜帶一個參數
@GET("user/login")
Call<LoginResponse> Login(@Query("name") String name);
- 攜帶2個或多個參數
@GET("user/login")
Call<LoginResponse> Login(@QueryMap Map<String,String> map);
@POST
post請求,分為一個參數,多個參數
- 攜帶一個參數
@FormUrlEncoded
@POST("user/login")
Call<LoginResponse> Login(@Field("name") String name);
- 攜帶2個或多個參數
@FormUrlEncoded
@POST("user/login")
Call<LoginResponse> Login(@FieldMap Map<String, String> map);
上面一些用法基本能滿足大多數日常開發,如果還有哪些需要說明的歡迎留言。
5.結合RxJava使用
RxJava相信就不用我多介紹了,有多好用我相信大家深有體會,不會用的小伙伴請自行百度,RxJava教程還是比較多的。如果要結合RxJava使用,其實也不難,這里給大家舉個栗子。
1. 首先把接口中的Call換成Observable,比如這樣
public interface Service {
@FormUrlEncoded
@POST("user/login")
Observable<LoginResponse> Login(@FieldMap Map<String, String> map);
2. 然后依然是前面的步驟,拿到Service對象
//因為接口定義的返回是Observable,所以這里可以直接鏈式調用
service.Login(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<LoginResponse>() {
@Override
public void accept(@NonNull LoginResponse loginResponse) throws Exception {
//請求完成,做自己的事
}
});
到此為止一個請求就完成了,大家可以對Retrofit做一個封裝,如果有時間,我之后也會給大家帶來Retrofit的封裝。