Retrofit 是一個 Restful API 的 HTTP 網絡請求框架的封裝,網絡請求的工作本質上是 OkHttp 完成,而 Retrofit 僅負責 網絡請求接口的封裝
注:Restful API瞭解請移步 RESTful API是什麼?
使用步驟
- 添加Retrofit庫的依賴:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
第一個是Retrofit依賴,後面是gson轉換需要用到
- 創建用於描述網絡請求 的接口
public interface ApiInterface {
@FormUrlEncoded
@POST("/lookup/findDictVersion.wx")
Observable<ResultBean> getVersion(@Field("customerId") String customerId);
}
- 發送請求
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://xxxx.aaaa.cn")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
apiInterface.getVersion("")
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ResultBean>() {
@Override
public void onSubscribe(Disposable d) {
Log.e("log","onSubscribe");
}
@Override
public void onNext(ResultBean value) {
Log.e("log",value.data.downUrl);
}
@Override
public void onError(Throwable e) {
Log.e("log","onError");
}
@Override
public void onComplete() {
Log.e("log","onComplete");
}
});
註解
網絡請求方式
標記
- @FormUrlEncoded
表示發送form-encoded的數據,每個鍵值對需要用@Filed來註解鍵名,隨後的對象需要提供值。 - @Multipart
表示發送form-encoded的數據(適用於有文件上傳的場景),每個鍵值對需要用@Part來註解鍵名,隨後的對象需要提供值。
public interface GetRequest_Interface {
/**
*表明是一個表單格式的請求(Content-Type:application/x-www-form-urlencoded)
* <code>Field("username")</code> 表示將後面的 <code>String name</code> 中name的取值作爲 username 的值
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
/**
* {@link Part} 後面支持三種類型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意類型
* 除 {@link okhttp3.MultipartBody.Part} 以外,其它類型都必須帶上表單字段({@link okhttp3.MultipartBody.Part} 中已經包含了表單字段的信息),
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
}
網絡請求參數
- @Header & @Headers
添加請求頭 &添加不固定的請求頭
// @Header
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
// @Headers
@Headers("Authorization: authorization")
@GET("user")
Call<User> getUser()
// 以上的效果是一致的。
// 區別在於使用場景和使用方式
// 1. 使用場景:@Header用於添加不固定的請求頭,@Headers用於添加固定的請求頭
// 2. 使用方式:@Header作用於方法的參數;@Headers作用於方法
- @Body
以 Post方式 傳遞 自定義數據類型 給服務器,如果提交的是一個Map,那麼作用相當於 @Field,不過Map要經過 FormBody.Builder 類處理成爲符合 Okhttp 格式的表單,如:
FormBody.Builder builder = new FormBody.Builder();
builder.add("key","value");
- @Field & @FieldMap
發送 Post請求 時提交請求的表單字段,與 @FormUrlEncoded 註解配合使用
public interface GetRequest_Interface {
/**
*表明是一個表單格式的請求(Content-Type:application/x-www-form-urlencoded)
* <code>Field("username")</code> 表示將後面的 <code>String name</code> 中name的取值作爲 username 的值
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
/**
* Map的key作爲表單的鍵
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);
}
- @Part & @PartMap
發送 Post請求 時提交請求的表單字段,與@Field的區別:功能相同,但攜帶的參數類型更加豐富,包括數據流,所以適用於 有文件上傳 的場景,與 @Multipart 註解配合使用
public interface GetRequest_Interface {
/**
* {@link Part} 後面支持三種類型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意類型
* 除 {@link okhttp3.MultipartBody.Part} 以外,其它類型都必須帶上表單字段({@link okhttp3.MultipartBody.Part} 中已經包含了表單字段的信息),
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
/**
* PartMap 註解支持一個Map作爲參數,支持 {@link RequestBody } 類型,
* 如果有其它的類型,會被{@link retrofit2.Converter}轉換,如後面會介紹的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter}
* 所以{@link MultipartBody.Part} 就不適用了,所以文件只能用<b> @Part MultipartBody.Part </b>
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file);
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args);
}
- @Query和@QueryMap
用於 @GET 方法的查詢參數(Query = Url 中 ‘?’ 後面的 key-value)
如:url = http://www.println.net/?cate=android,其中,Query = cate
配置時只需要在接口方法中增加一個參數即可:
@GET("/")
Call<String> cate(@Query("cate") String cate);
- @Path
URL地址的缺省值
public interface GetRequest_Interface {
@GET("users/{user}/repos")
Call<ResponseBody> getBlog(@Path("user") String user );
// 訪問的API是:https://api.github.com/users/{user}/repos
// 在發起請求時, {user} 會被替換爲方法的第一個參數 user(被@Path註解作用)
}
- @Url
直接傳入一個請求的 URL變量 用於URL設置
public interface GetRequest_Interface {
@GET
Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
// 當有URL註解時,@GET傳入的URL就可以省略
// 當GET、POST...HTTP等方法中沒有設置Url時,則必須使用 {@link Url}提供
}