@Query,@QueryMap,@Field,@FieldMap,@FormUrlEncoded,@Path,@Url
這七種注解應(yīng)該是最常用的了。
下邊列舉各種應(yīng)用場(chǎng)景。
Retrofit retrofit =newRetrofit.Builder()
.baseUrl("https://api.github.com/")
.build();publicinterfaceGitHubService {//無參數(shù)@GET("users/stven0king/repos")
Call>listRepos();//少數(shù)參數(shù)@GET("users/stven0king/repos")
Call> listRepos(@Query("time")longtime);//參數(shù)較多@GET("users/stven0king/repos")
Call> listRepos(@QueryMap Mapparams);
}
@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 =newRetrofit.Builder()
.baseUrl("https://api.github.com/")
.build()publicinterfaceGitHubService {//無參數(shù)@POST("users/stven0king/repos")
Call>listRepos();//少數(shù)參數(shù)@FormUrlEncoded
@POST("users/stven0king/repos")
Call> listRepos(@Field("time")longtime);//參數(shù)較多@FormUrlEncoded
@POST("users/stven0king/repos")
Call> listRepos(@FieldMap Mapparams);
}
@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 =newRetrofit.Builder()
.baseUrl("https://api.github.com/")
.build()publicinterfaceGitHubService {
@GET("users/{user}/repos")
Call> listRepos(@Path("user") String user);
}
四、動(dòng)態(tài)的url地址請(qǐng)求
Retrofit retrofit =newRetrofit.Builder()
.baseUrl("https://api.github.com/")
.build()publicinterfaceGitHubService {
@GET
Call>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吧。