編輯:關於 Android 程式設計
上一篇我們掌握了 Retrofit 最基礎的 GET 請求寫法,並對請求參數有了初步認識。本篇會把 Retrofit2 提供的各類請求參數注解系統梳理一遍,包括路徑替換、查詢參數、表單提交、JSON 請求體、文件上傳以及消息報頭。所有示例仍以淘寶 IP 庫接口為例。
@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:
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 數據類型。淘寶 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 字符串作為請求體發送:
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); Callcall = 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 庫並不支持這種數據類型,所以不會返回我們期望的地理信息數據——這恰好反過來驗證了請求體格式是正確的。
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"));
@Multipart
@POST("user/photo")
Call updateUser(@PartMap Map photos,
@Part("description") RequestBody description);
與單文件上傳思路相同,只是把文件集合封裝進 Map,再用 @PartMap 標示,其餘流程不變。
在實際的 HTTP 請求中,出於防止攻擊、過濾不安全訪問或添加自定義加密標識等目的,通常會在報頭中攜帶一些特殊信息,以減輕服務端壓力並保證請求安全。Retrofit 提供了兩種添加報頭的方式。
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();
}
interface SomeService {
@GET("some/endpoint")
Call getCarType(@Header("Location") String location);
}
使用 @Header 之後,每次調用方法時都可以傳入不同的報頭值,靈活性更高。
把這些注解放在一起看,規律其實很清晰:@Path 改路徑,@Query / @QueryMap 拼查詢串,@Field / @Body / @Part / @PartMap 組織請求體,@Header / @Headers 處理報頭。記住這條主線,Retrofit 的接口定義基本就沒有障礙了。
一篇搞懂 Android SDK 目錄結構與版本號的區別
總有人問:Tools、Build-Tools、Platform-Tools 到底有什麼區別,各自是幹嘛用的?今天就把 SDK 目錄做個系統性的梳理。SDK 目錄結構add
微信收藏如何導出到電腦?兩種方法整理
若想備份微信收藏內容,可嘗試以下兩種方式。方法一:複製本機資料圖片通常位於 Tencent/MicroMsg/camera;文件則位於 sdcard 的 Tencent/
Android 基礎入門教程——Bitmap(位圖)全解析 Part 1
本節引言 上一節我們講解了 Android 中 13 種 Drawable 類型,不知道你有沒有應用到自己的項目裡?本節要探討 Bitmap(位圖)的使用。開始之前,先
Android ViewPager 畫廊效果:一次顯示多張圖片與滑動實現
ViewPager 本身通常一次只顯示一頁,但透過 clipChildren 屬性與適當的 margin,可以讓左右頁面的內容露出,形成類似畫廊的視覺效果。 關鍵設定