Retrofit2.0中注解使用方式


之前有講過Retrofit2.0的簡單使用和解析。最近在做Retrofit替換之前使用的AsyncHttpClient,在替換的過程中遇到一些之前忽視的小細節。自己感覺知道這幾點在開發中靈活使用Retrofit非常有好處。

說說Retrofit中的注解

@Query,@QueryMap,@Field,@FieldMap,@FormUrlEncoded,@Path,@Url 
這七種注解應該是最常用的了。

下邊列舉各種應用場景。

一、get方式請求靜態url地址

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();
public interface GitHubService {
    //無參數
    @GET("users/stven0king/repos")
    Call<List<Repo>> listRepos();
    //少數參數
    @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);
}

 

@Query和@QueryMap也可以結合在一起使用。

要是對應的url在服務端支持get/post兩種類型的請求的話,那么上面的@GET變為@POST也可以執行,只不過post請求時所帶的參數也會像get方式一樣已?key=value&key1=vaule2…的形式拼接在url的后邊。

二、post方式請求靜態url地址

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build()
public interface GitHubService {
    //無參數
    @POST("users/stven0king/repos")
    Call<List<Repo>> listRepos();
    //少數參數
    @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);
}


@Field和@FieldMap可以結合在一起使用。

另外是不是發現了比起@GET多了一個@FromUrlEncoded的注解。如果去掉@FromUrlEncoded在post請求中使用@Field和@FieldMap,那么程序會拋出java.lang.IllegalArgumentException: @Field parameters can only be used with form encoding. (parameter #1)的錯誤異常。如果將@FromUrlEncoded添加在@GET上面呢,同樣的也會拋出java.lang.IllegalArgumentException:FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).的錯誤異常

三、半靜態的url地址請求

 
        
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);
}

四、動態的url地址請求

 
        
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build()

public interface GitHubService {
  @GET
  Call<List<Repo>> listRepos(@Url String user);
}

五、總結小細節

  • 當@GET或@POST注解的url為全路徑時(可能和baseUrl不是一個域),會直接使用注解的url的域。
  • 如果請求為post實現,那么最好傳遞參數時使用@Field、@FieldMap和@FormUrlEncoded。因為@Query和或QueryMap都是將參數拼接在url后面的,而@Field或@FieldMap傳遞的參數時放在請求體的。
  • 使用@Path時,path對應的路徑不能包含”/”,否則會將其轉化為%2F。在遇到想動態的拼接多節url時,還是使用@Url吧。
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM