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

Retrofit 使用詳解:下載與多文件上傳

編輯:關於 Android 程式設計

Retrofit 提供了 5 種內置注解:GET、POST、PUT、DELETE 和 HEAD,在注解中指定資源的相對 URL。

URL 與參數小總結

@GET("users/list")

也可以在 URL 中直接指定查詢參數:

@GET("users/list?sort=desc")

請求 URL 可以在函數中用替換塊和參數動態更新,替換塊由 { } 包圍的字母數字組成,對應參數需用相同字符串並以 @Path 註解:

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

准備工作

Retrofit 初始化:

public static ZoneApiInterface getClient() {
    Retrofit retrofit2 = new Retrofit.Builder()
        .baseUrl(Constant.ADDRESS_RetrofitClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    return retrofit2.create(ZoneApiInterface.class);
}

API 接口與 callback 回調:

static Callback<Data> callback = new Callback<Data>() {
    @Override
    public void onResponse(Call<Data> call, Response<Data> response) {
        System.out.println("url:" + call.request().url() + "\t --->" + new Gson().toJson(response.body()));
    }
    @Override
    public void onFailure(Call<Data> call, Throwable t) {
        t.printStackTrace();
    }
};

GET 請求

@Query 對應 url 中 ? 後面的查詢參數:

@GET("{user}")
Call<Data> getZone(@Path("user") String user, @Query("name") String str);
getClient().getZone("log", "Zone").enqueue(callback);

@QueryMap:

@GET("{user}")
Call<Data> getZone(@Path("user") String user, @QueryMap Map<String, String> map);

@Url:Retrofit 2.0 新增的注解,允許直接傳入完整的請求 URL,方便把上一個請求獲得的 url 直接傳入:

Call<Data> getZoneUrl(@Url String str);
getClient().getZoneUrl("https://101.40.6.224:8089/Test/log" + "?a=1").enqueue(callback);

這個會無視 baseUrl。

POST

@Body 可指定一個對象作為請求體:

@POST("users/new")
Call<User> createUser(@Body User user);

@Body 傳 Map 時:

@POST("{user}")
Call<Data> postZone(@Path("user") String user, @Body Map<String, String> map);
getClient().postZone("log", map).enqueue(callback);

上傳

1. 最標準的方式,使用 MultipartBody(此時服務端 item.isFormField() = false):

@POST("log")
Call<Data> postZoneFile(@Body MultipartBody mb);
//多文件上傳
MultipartBody.Builder form = new MultipartBody.Builder();
form.setType(MultipartBody.FORM);
form.addFormDataPart("keyName", "Zone");
form.addFormDataPart("file", "gaga.jpg", RequestBody.create(MediaType.parse("image/*"), file1));
form.addFormDataPart("file2", "meinv.jpg", RequestBody.create(MediaType.parse("image/*"), file));
getClient().postZoneFile(form.build()).enqueue(callback);

2. 使用 @Multipart(此時 item.isFormField() = true):

@Multipart
@POST("log")
Call<Data> sendFile(@Part(value = "myFile", encoding = "utf-8") RequestBody file);
@Multipart
@POST("log")
Call<Data> sendFiles(@PartMap Map<String, RequestBody> params);
HashMap<String, RequestBody> mapFile = new HashMap<>();
mapFile.put("keyName", RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "Zone"));
mapFile.put("file1", RequestBody.create(MediaType.parse("image/*"), file));
getClient().sendFiles(mapFile).enqueue(callback);

下載

下載時需要加上 @Streaming 注解:

@GET
@Streaming
public Call<ResponseBody> down(@Url String url);
getClient().down(downUrl).enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        // 處理下載的流
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) { }
});

Form encoded

使用 @FormUrlEncoded 發送表單數據,配合 @Field 指定每個表單項的 Key;參數較多時可用 @FieldMap 與 Map 對象:

@FormUrlEncoded
@POST("log")
Call<Data> formUrlEncoded(@Field("name") String name, @Field("password") String password);
@FormUrlEncoded
@POST("log")
Call<Data> formUrlEncodedFile(@FieldMap Map<String, String> map);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved