個(gè)人博客地址 http://dandanlove.com/
之前有講過Retrofit2.0的簡(jiǎn)單使用和解析。最近在做Retrofit替換之前使用的AsyncHttpClient,在替換的過程中遇到一些之前忽視的小細(xì)節(jié)。自己感覺知道這幾點(diǎn)在開發(fā)中靈活使用Retrofit非常有好處。
說說Retrofit中的注解
@Query,@QueryMap,@Field,@FieldMap,@FormUrlEncoded,@Path,@Url
這七種注解應(yīng)該是最常用的了。
下邊列舉各種應(yīng)用場(chǎng)景。
一、get方式請(qǐng)求靜態(tài)url地址
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
public interface GitHubService {
//無參數(shù)
@GET("users/stven0king/repos")
Call<List<Repo>> listRepos();
//少數(shù)參數(shù)
@GET("users/stven0king/repos")
Call<List<Repo>> listRepos(@Query("time") long time);
//參數(shù)較多
@GET("users/stven0king/repos")
Call<List<Repo>> listRepos(@QueryMap Map<String, String> params);
}
@Query和@QueryMap也可以結(jié)合在一起使用。
要是對(duì)應(yīng)的url在服務(wù)端支持get/post兩種類型的請(qǐng)求的話,那么上面的@GET變?yōu)锧POST也可以執(zhí)行,只不過post請(qǐng)求時(shí)所帶的參數(shù)也會(huì)像get方式一樣已?key=value&key1=vaule2...的形式拼接在url的后邊。
二、post方式請(qǐng)求靜態(tài)url地址
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build()
public interface GitHubService {
//無參數(shù)
@POST("users/stven0king/repos")
Call<List<Repo>> listRepos();
//少數(shù)參數(shù)
@FormUrlEncoded
@POST("users/stven0king/repos")
Call<List<Repo>> listRepos(@Field("time") long time);
//參數(shù)較多
@FormUrlEncoded
@POST("users/stven0king/repos")
Call<List<Repo>> listRepos(@FieldMap Map<String, String> params);
}
@Field和@FieldMap可以結(jié)合在一起使用。
另外是不是發(fā)現(xiàn)了比起@GET多了一個(gè)@FromUrlEncoded的注解。如果去掉@FromUrlEncoded在post請(qǐng)求中使用@Field和@FieldMap,那么程序會(huì)拋出
java.lang.IllegalArgumentException: @Field parameters can only be used with form encoding. (parameter #1)
的錯(cuò)誤異常。如果將@FromUrlEncoded添加在@GET上面呢,同樣的也會(huì)拋出java.lang.IllegalArgumentException:FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).
的錯(cuò)誤異常。
三、半靜態(tài)的url地址請(qǐng)求
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build()
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
四、動(dòng)態(tài)的url地址請(qǐng)求
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build()
public interface GitHubService {
@GET
Call<List<Repo>> listRepos(@Url String user);
}
五、總結(jié)小細(xì)節(jié)
- 當(dāng)@GET或@POST注解的url為全路徑時(shí)(可能和baseUrl不是一個(gè)域),會(huì)直接使用注解的url的域。
- 如果請(qǐng)求為post實(shí)現(xiàn),那么最好傳遞參數(shù)時(shí)使用@Field、@FieldMap和@FormUrlEncoded。因?yàn)锧Query和或QueryMap都是將參數(shù)拼接在url后面的,而@Field或@FieldMap傳遞的參數(shù)時(shí)放在請(qǐng)求體的。
- 使用@Path時(shí),path對(duì)應(yīng)的路徑不能包含"/",否則會(huì)將其轉(zhuǎn)化為%2F。在遇到想動(dòng)態(tài)的拼接多節(jié)url時(shí),還是使用@Url吧。
想閱讀作者的更多文章,可以查看我 個(gè)人博客 和公共號(hào):