參考文獻(xiàn):
Retrofit2.0使用詳解
Retrofit 2.0 注解篇
1.Retrofit2的簡(jiǎn)單使用:
1.不用說(shuō)關(guān)聯(lián)類庫(kù):
compile 'com.squareup.retrofit2:retrofit:2.3.0'
這里我引入的是最新的你也可以看看最新的是什么版本
2.定義接口
這個(gè)接口主要寫請(qǐng)求是用到的一些數(shù)據(jù)
public interface RetrofitApi {
@GET("repos/{owner}/{repo}/contributors")
Call<String> contributorsBySimpleGetCall(@Part("owner") String owner, @Path("repo") String repo);
}
這里面是采用注釋的形式去關(guān)聯(lián)網(wǎng)絡(luò)請(qǐng)求的,其實(shí)關(guān)于Retrofit2的網(wǎng)絡(luò)請(qǐng)求都是基于注釋去進(jìn)行了,具體的原理我也不太清楚,等到自己技術(shù)層次提升的時(shí)候在去進(jìn)行研究把。。。
3.創(chuàng)建Retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
這里注意Url地址后面的"/"號(hào)這個(gè)一定要有!如果你想要在那個(gè)接口中加是不行的!
4.構(gòu)建請(qǐng)求接口的實(shí)體
RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);
這個(gè)實(shí)體是根據(jù)上面那個(gè)接口生成的;
5.創(chuàng)建請(qǐng)求
Call<ResponseBody> responseBodyCall = retrofitApi.contributorsBySimpleGetCall("square", "retrofit");
這里主要是完善請(qǐng)求的參數(shù),或者請(qǐng)求的具體內(nèi)容
6.創(chuàng)建回調(diào)
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e(TAG, "onResponse: 成功" + response.body());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "onFailure: 失敗" + t.toString());
}
});
7.清除請(qǐng)求
responseBodyCall.cancel();
以上就完成了基本的請(qǐng)求,回調(diào)是回調(diào)到主線程的,這點(diǎn)的話比OkHttp3好點(diǎn)!
下面來(lái)說(shuō)說(shuō)常用的注解:
1.請(qǐng)求方法注解
| 序號(hào) | 名稱 |
|---|---|
| @GET | get請(qǐng)求 |
| @POST | post請(qǐng)求 |
常用的請(qǐng)求就這兩個(gè),其他的我就沒(méi)寫,這些注解都是用在方法體前面的,用于標(biāo)明請(qǐng)求的方法
@GET("repos/{owner}/{repo}/contributors")
Call<String> contributorsBySimpleGetCall(@Part("owner") String owner, @Path("repo") String repo);
2.@path注解
這個(gè)的作用和占位符的作用類似,
@GET("repos/{owner}/{repo}/contributors")
Call<String> contributorsBySimpleGetCall(@Part("owner") String owner, @Path("repo") String repo);
還是那這個(gè)方法舉例,上面用或括號(hào)括起來(lái)的就相當(dāng)于占位,具體的定義值實(shí)在下面進(jìn)行的通過(guò)@Path替換花括號(hào)內(nèi)的名稱。
3.@Query和@QueryMap(用于GET請(qǐng)求的注解)
這兩個(gè)是將請(qǐng)求參數(shù)加載末尾的方法;
@GET("users/stven0king/repos")
Call<List<Repo>> listRepos(@Query("time") long time);
@GET("users/stven0king/repos")
Call<List<Repo>> listRepos(@QueryMap Map<String, String> params);
區(qū)別在于@Query后面跟的是一個(gè)參數(shù)而@Query后面跟的是一個(gè)數(shù)組,也就是多個(gè)參數(shù)
4.@Field和@FieldMap(用于POST請(qǐng)求的注解)
@FormUrlEncoded
@POST("users/stven0king/repos")
Call<List<Repo>> listRepos(@Field("time") long time);
@FormUrlEncoded
@POST("users/stven0king/repos")
Call<List<Repo>> listRepos(@FieldMap Map<String, String> params);
這里要注意上面的@FormUrlEncoded如果沒(méi)有這個(gè)的話會(huì)拋異常的
5.@Url(用于動(dòng)態(tài)的Url地址請(qǐng)求)
@GET
Call<List<Repo>> listRepos(@Url String user);
其他操作符的話以后用到的時(shí)候再去研究把。。。