Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網絡編程(十):Retrofit2 請求參數注解全解

編輯:關於 Android 程式設計

前言

上一篇我們掌握了 Retrofit 最基礎的 GET 請求寫法,並對請求參數有了初步認識。本篇會把 Retrofit2 提供的各類請求參數注解系統梳理一遍,包括路徑替換、查詢參數、表單提交、JSON 請求體、文件上傳以及消息報頭。所有示例仍以淘寶 IP 庫接口為例。

一、GET 請求

動態配置 URL 路徑:@Path

@Path 用於替換 URL 中的佔位符,非常適合 base 路徑需要動態變化的場景。

public interface IpServiceForPath {
    @GET("{path}/getIpInfo.php?ip=59.108.54.37")
    Call getIpMsg(@Path("path") String path);
}

此處 @GET 裡的 {path} 對應 @Path("path"),實際替換的值來自傳入的 String path。

String url = "https://ip.taobao.com/";
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

IpServiceForPath ipService = retrofit.create(IpServiceForPath.class);
Call call = ipService.getIpMsg("service"); // 傳入 service 替換 {path}

call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        String country = response.body().getData().getCountry();
        Toast.makeText(getApplicationContext(), country, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call call, Throwable t) { }
});

動態指定查詢條件:@Query 與 @QueryMap

單個查詢參數用 @Query:

public interface IpServiceForQuery {
    @GET("getIpInfo.php")
    Call getIpMsg(@Query("ip") String ip);
}

但實際業務中往往需要傳入大量查詢參數,一個個寫 @Query 既冗長又難維護。這時可以改用 @QueryMap,把所有參數收攏到一個 Map 裡統一傳遞:

public interface IpServiceForQueryMap {
    @GET("getIpInfo.php")
    Call getIpMsg(@QueryMap Map options);
}

二、POST 請求

鍵值對表單:@Field

這是最常用的 POST 數據類型。淘寶 IP 庫支持表單形式的 POST 請求:

public interface IpServiceForPost {
    @FormUrlEncoded
    @POST("getIpInfo.php")
    Call getIpMsg(@Field("ip") String first);
}

關鍵是 @FormUrlEncoded 注解,它標明這是一個表單請求;隨後 @Field 標示參數對應的鍵名,最終組裝成鍵值對提交。

String url = "https://ip.taobao.com/service/";
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

IpServiceForPost ipService = retrofit.create(IpServiceForPost.class);
Call call = ipService.getIpMsg("59.108.54.37");

call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        String country = response.body().getData().getCountry();
        Toast.makeText(getApplicationContext(), country, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call call, Throwable t) { }
});

JSON 請求體:@Body

也可以把對象序列化成 JSON 字符串作為請求體發送:

public interface IpServiceForPostBody {
    @POST("getIpInfo.php")
    Call getIpMsg(@Body Ip ip);
}

只需用 @Body 標識參數對象,Retrofit 會自動把它轉換為 JSON。

public class Ip {
    private String ip;

    public Ip(String ip) {
        this.ip = ip;
    }
}

請求部分的代碼與前面基本一致:

IpServiceForPostBody ipService = retrofit.create(IpServiceForPostBody.class);
Call call = ipService.getIpMsg(new Ip(ip));

call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        String country = response.body().getData().getCountry();
        Toast.makeText(getApplicationContext(), country, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call call, Throwable t) { }
});

用 Fiddler 抓包可以看到,請求體確實是一段 JSON 字符串:

由於淘寶 IP 庫並不支持這種數據類型,所以不會返回我們期望的地理信息數據——這恰好反過來驗證了請求體格式是正確的。

單個文件上傳:@Part

public interface UploadFileForPart {
    @Multipart
    @POST("user/photo")
    Call updateUser(@Part MultipartBody.Part photo,
                         @Part("description") RequestBody description);
}

@Multipart 表示這次請求可以攜帶多個 @Part。第一個參數使用 MultipartBody.Part 類型承載文件,另一個參數用 RequestBody 傳遞普通鍵值對。

File file = new File(Environment.getExternalStorageDirectory(), "wangshu.png");
RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file);

MultipartBody.Part photo = MultipartBody.Part.createFormData(
        "photos", "wangshu.png", photoRequestBody);

UploadFileForPart uploadFile = retrofit.create(UploadFileForPart.class);
Call call = uploadFile.updateUser(photo, RequestBody.create(null, "wangshu"));

多個文件上傳:@PartMap

@Multipart
@POST("user/photo")
Call updateUser(@PartMap Map photos,
                     @Part("description") RequestBody description);

與單文件上傳思路相同,只是把文件集合封裝進 Map,再用 @PartMap 標示,其餘流程不變。

三、消息報頭 Header

在實際的 HTTP 請求中,出於防止攻擊、過濾不安全訪問或添加自定義加密標識等目的,通常會在報頭中攜帶一些特殊信息,以減輕服務端壓力並保證請求安全。Retrofit 提供了兩種添加報頭的方式。

靜態方式:@Headers

interface SomeService {
    @GET("some/endpoint")
    @Headers("Accept-Encoding: application/json")
    Call getCarType();
}

需要添加多個報頭時,用花括號包裹:

interface SomeService {
    @GET("some/endpoint")
    @Headers({
        "Accept-Encoding: application/json",
        "User-Agent: MoonRetrofit"
    })
    Call getCarType();
}

動態方式:@Header

interface SomeService {
    @GET("some/endpoint")
    Call getCarType(@Header("Location") String location);
}

使用 @Header 之後,每次調用方法時都可以傳入不同的報頭值,靈活性更高。

小結

把這些注解放在一起看,規律其實很清晰:@Path 改路徑,@Query / @QueryMap 拼查詢串,@Field / @Body / @Part / @PartMap 組織請求體,@Header / @Headers 處理報頭。記住這條主線,Retrofit 的接口定義基本就沒有障礙了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved