Retrofit用法詳解

轉載地址:http://blog.csdn.net/duanyy1990/article/details/52139294


一、 簡介

Retrofit是Square公司開發的一款針對Android網絡請求的框架,Retrofit2底層基於OkHttp實現的,OkHttp現在已經得到Google官方認可,大量的app都採用OkHttp做網絡請求,其源碼詳見OkHttp Github

本文全部是在Retrofit2.0+版本基礎上論述,所用例子全部來自豆瓣Api

首先先來看一個完整Get請求是如何實現:

  1. 創建業務請求接口,具體代碼如下:

    public interface BlueService {
       @GET("book/search")
       Call<BookSearchResponse> getSearchBooks(@Query("q") String name, 
            @Query("tag") String tag, @Query("start") int start, 
            @Query("count") int count);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    這裏需要稍作說明,@GET註解就表示get請求,@Query表示請求參數,將會以key=value的方式拼接在url後面

  2. 需要創建一個Retrofit的示例,並完成相應的配置

    Retrofit retrofit = new Retrofit.Builder()
       .baseUrl("https://api.douban.com/v2/")
       .addConverterFactory(GsonConverterFactory.create())
       .build();
    
    BlueService service = retrofit.create(BlueService.class);
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    這裏的baseUrl就是網絡請求URL相對固定的地址,一般包括請求協議(如Http)、域名或IP地址、端口號等,當然還會有很多其他的配置,下文會詳細介紹。還有addConverterFactory方法表示需要用什麼轉換器來解析返回值,GsonConverterFactory.create()表示調用Gson庫來解析json返回值,具體的下文還會做詳細介紹。

  3. 調用請求方法,並得到Call實例

    Call<BookSearchResponse> call = mBlueService.getSearchBooks("小王子", "", 0, 3);
    • 1
    • 1

    Call其實在Retrofit中就是行使網絡請求並處理返回值的類,調用的時候會把需要拼接的參數傳遞進去,此處最後得到的url完整地址爲

    https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&tag=&start=0&count=3

  4. 使用Call實例完成同步或異步請求

    • 同步請求

      BookSearchResponse response = call.execute().body();
      • 1
      • 1

      這裏需要注意的是網絡請求一定要在子線程中完成,不能直接在UI線程執行,不然會crash

    • 異步請求

      call.enqueue(new Callback<BookSearchResponse>() {
      @Override
      public void onResponse(Call<BookSearchResponse> call,        Response<BookSearchResponse> response) {
      asyncText.setText("異步請求結果: " + response.body().books.get(0).altTitle);
      }
      @Override
      public void onFailure(Call<BookSearchResponse> call, Throwable t) {
      
      }
      });
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10

二、如何使用

首先需要在build.gradle文件中引入需要的第三包,配置如下:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

引入完第三包接下來就可以使用Retrofit來進行網絡請求了。接下來會對不同的請求方式做進一步的說明。

Get方法

1. @Query

Get方法請求參數都會以key=value的方式拼接在url後面,Retrofit提供了兩種方式設置請求參數。第一種就是像上文提到的直接在interface中添加@Query註解,還有一種方式是通過Interceptor實現,直接看如何通過Interceptor實現請求參數的添加。

public class CustomInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl httpUrl = request.url().newBuilder()
                .addQueryParameter("token", "tokenValue")
                .build();
        request = request.newBuilder().url(httpUrl).build();
        return chain.proceed(request);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

addQueryParameter就是添加請求參數的具體代碼,這種方式比較適用於所有的請求都需要添加的參數,一般現在的網絡請求都會添加token作爲用戶標識,那麼這種方式就比較適合。

創建完成自定義的Interceptor後,還需要在Retrofit創建client處完成添加

addInterceptor(new CustomInterceptor())
  • 1
  • 1
2. @QueryMap

如果Query參數比較多,那麼可以通過@QueryMap方式將所有的參數集成在一個Map統一傳遞,還以上文中的get請求方法爲例

public interface BlueService {
    @GET("book/search")
    Call<BookSearchResponse> getSearchBooks(@QueryMap Map<String, String> options);
}
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

調用的時候將所有的參數集合在統一的map中即可

Map<String, String> options = new HashMap<>();
map.put("q", "小王子");
map.put("tag", null);
map.put("start", "0");
map.put("count", "3");
Call<BookSearchResponse> call = mBlueService.getSearchBooks(options);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
3. Query集合

假如你需要添加相同Key值,但是value卻有多個的情況,一種方式是添加多個@Query參數,還有一種簡便的方式是將所有的value放置在列表中,然後在同一個@Query下完成添加,實例代碼如下:

public interface BlueService {
    @GET("book/search")
    Call<BookSearchResponse> getSearchBooks(@Query("q") List<String> name);
}
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

最後得到的url地址爲

https://api.douban.com/v2/book/search?q=leadership&q=beyond%20feelings
  • 1
  • 1
4. Query非必填

如果請求參數爲非必填,也就是說即使不傳該參數,服務端也可以正常解析,那麼如何實現呢?其實也很簡單,請求方法定義處還是需要完整的Query註解,某次請求如果不需要傳該參數的話,只需填充null即可。

針對文章開頭提到的get的請求,加入按以下方式調用

Call<BookSearchResponse> call = mBlueService.getSearchBooks("小王子", null, 0, 3);
  • 1
  • 1

那麼得到的url地址爲

https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&start=0&count=3
  • 1
  • 1
5. @Path

如果請求的相對地址也是需要調用方傳遞,那麼可以使用@Path註解,示例代碼如下:

@GET("book/{id}")
Call<BookResponse> getBook(@Path("id") String id);
  • 1
  • 2
  • 1
  • 2

業務方想要在地址後面拼接書籍id,那麼通過Path註解可以在具體的調用場景中動態傳遞,具體的調用方式如下:

 Call<BookResponse> call = mBlueService.getBook("1003078");
  • 1
  • 1

此時的url地址爲

https://api.douban.com/v2/book/1003078
  • 1
  • 1

@Path可以用於任何請求方式,包括Post,Put,Delete等等

Post請求

1. @field

Post請求需要把請求參數放置在請求體中,而非拼接在url後面,先來看一個簡單的例子

 @FormUrlEncoded
 @POST("book/reviews")
 Call<String> addReviews(@Field("book") String bookId, @Field("title") String title,
 @Field("content") String content, @Field("rating") String rating);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

這裏有幾點需要說明的

  • @FormUrlEncoded將會自動將請求參數的類型調整爲application/x-www-form-urlencoded,假如content傳遞的參數爲Good Luck,那麼最後得到的請求體就是

    content=Good+Luck
    • 1
    • 1

    FormUrlEncoded不能用於Get請求

  • @Field註解將每一個請求參數都存放至請求體中,還可以添加encoded參數,該參數爲boolean型,具體的用法爲

    @Field(value = "book", encoded = true) String book
    • 1
    • 1

    encoded參數爲true的話,key-value-pair將會被編碼,即將中文和特殊字符進行編碼轉換

2. @FieldMap

上述Post請求有4個請求參數,假如說有更多的請求參數,那麼通過一個一個的參數傳遞就顯得很麻煩而且容易出錯,這個時候就可以用FieldMap

 @FormUrlEncoded
 @POST("book/reviews")
 Call<String> addReviews(@FieldMap Map<String, String> fields);
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
3. @Body

如果Post請求參數有多個,那麼統一封裝到類中應該會更好,這樣維護起來會非常方便

@FormUrlEncoded
@POST("book/reviews")
Call<String> addReviews(@Body Reviews reviews);

public class Reviews {
    public String book;
    public String title;
    public String content;
    public String rating;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

其他請求方式

除了Get和Post請求,Http請求還包括Put,Delete等等,用法和Post相似,所以就不再單獨介紹了。

上傳

上傳因爲需要用到Multipart,所以需要單獨拿出來介紹,先看一個具體上傳的例子

首先還是需要新建一個interface用於定義上傳方法

public interface FileUploadService {  
    // 上傳單個文件
    @Multipart
    @POST("upload")
    Call<ResponseBody> uploadFile(
            @Part("description") RequestBody description,
            @Part MultipartBody.Part file);

    // 上傳多個文件
    @Multipart
    @POST("upload")
    Call<ResponseBody> uploadMultipleFiles(
            @Part("description") RequestBody description,
            @Part MultipartBody.Part file1,
            @Part MultipartBody.Part file2);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

接下來我們還需要在Activity和Fragment中實現兩個工具方法,代碼如下:

public static final String MULTIPART_FORM_DATA = "multipart/form-data";

@NonNull
private RequestBody createPartFromString(String descriptionString) {  
    return RequestBody.create(
            MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
}

@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {  
    File file = FileUtils.getFile(this, fileUri);

    // 爲file建立RequestBody實例
    RequestBody requestFile =
        RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);

    // MultipartBody.Part藉助文件名完成最終的上傳
    return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

好了,接下來就是最終的上傳文件代碼了

Uri file1Uri = ... // 從文件選擇器或者攝像頭中獲取 
Uri file2Uri = ... 

// 創建上傳的service實例
FileUploadService service =  
        ServiceGenerator.createService(FileUploadService.class);

// 創建文件的part (photo, video, ...)
MultipartBody.Part body1 = prepareFilePart("video", file1Uri);  
MultipartBody.Part body2 = prepareFilePart("thumbnail", file2Uri);

// 添加其他的part
RequestBody description = createPartFromString("hello, this is description speaking");

// 最後執行異步請求操作
Call<ResponseBody> call = service.uploadMultipleFiles(description, body1, body2);  
call.enqueue(new Callback<ResponseBody>() {  
    @Override
    public void onResponse(Call<ResponseBody> call,
            Response<ResponseBody> response) {
        Log.v("Upload", "success");
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e("Upload error:", t.getMessage());
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

三、其他必須知道的事項

1. 添加自定義的header

Retrofit提供了兩個方式定義Http請求頭參數:靜態方法和動態方法,靜態方法不能隨不同的請求進行變化,頭部信息在初始化的時候就固定了。而動態方法則必須爲每個請求都要單獨設置。

  • 靜態方法

    public interface BlueService {
    @Headers("Cache-Control: max-age=640000")
      @GET("book/search")
      Call<BookSearchResponse> getSearchBooks(@Query("q") String name, 
            @Query("tag") String tag, @Query("start") int start, 
            @Query("count") int count);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    當然你想添加多個header參數也是可以的,寫法也很簡單

    public interface BlueService {
    @Headers({
          "Accept: application/vnd.yourapi.v1.full+json",
          "User-Agent: Your-App-Name"
      })
      @GET("book/search")
      Call<BookSearchResponse> getSearchBooks(@Query("q") String name, 
            @Query("tag") String tag, @Query("start") int start, 
            @Query("count") int count);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    此外也可以通過Interceptor來定義靜態請求頭

    public class RequestInterceptor implements Interceptor {
      @Override
      public Response intercept(Chain chain) throws IOException {
          Request original = chain.request();
          Request request = original.newBuilder()
              .header("User-Agent", "Your-App-Name")
              .header("Accept", "application/vnd.yourapi.v1.full+json")
              .method(original.method(), original.body())
              .build();
          return chain.proceed(request);
      }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    添加header參數Request提供了兩個方法,一個是header(key, value),另一個是.addHeader(key, value),兩者的區別是,header()如果有重名的將會覆蓋,而addHeader()允許相同key值的header存在

    然後在OkHttp創建Client實例時,添加RequestInterceptor即可

    private static OkHttpClient getNewClient(){
    return new OkHttpClient.Builder()
      .addInterceptor(new RequestInterceptor())
      .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
      .build();
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 動態方法

    public interface BlueService {
      @GET("book/search")
      Call<BookSearchResponse> getSearchBooks(
      @Header("Content-Range") String contentRange, 
      @Query("q") String name, @Query("tag") String tag, 
      @Query("start") int start, @Query("count") int count);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

2. 網絡請求日誌

調試網絡請求的時候經常需要關注一下請求參數和返回值,以便判斷和定位問題出在哪裏,Retrofit官方提供了一個很方便查看日誌的Interceptor,你可以控制你需要的打印信息類型,使用方法也很簡單。

首先需要在build.gradle文件中引入logging-interceptor

compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
  • 1
  • 1

同上文提到的CustomInterceptor和RequestInterceptor一樣,添加到OkHttpClient創建處即可,完整的示例代碼如下:

private static OkHttpClient getNewClient(){
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    return new OkHttpClient.Builder()
           .addInterceptor(new CustomInterceptor())
           .addInterceptor(logging)
           .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
           .build();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

HttpLoggingInterceptor提供了4中控制打印信息類型的等級,分別是NONE,BASIC,HEADERS,BODY,接下來分別來說一下相應的打印信息類型。

  • NONE

    沒有任何日誌信息

  • Basic

    打印請求類型,URL,請求體大小,返回值狀態以及返回值的大小

    D/HttpLoggingInterceptor$Logger: --> POST /upload HTTP/1.1 (277-byte body)  
    D/HttpLoggingInterceptor$Logger: <-- HTTP/1.1 200 OK (543ms, -1-byte body)  
    • 1
    • 2
    • 1
    • 2
  • Headers

    打印返回請求和返回值的頭部信息,請求類型,URL以及返回值狀態碼

    <-- 200 OK https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&start=0&count=3&token=tokenValue (3787ms)
    D/OkHttp: Date: Sat, 06 Aug 2016 14:26:03 GMT
    D/OkHttp: Content-Type: application/json; charset=utf-8
    D/OkHttp: Transfer-Encoding: chunked
    D/OkHttp: Connection: keep-alive
    D/OkHttp: Keep-Alive: timeout=30
    D/OkHttp: Vary: Accept-Encoding
    D/OkHttp: Expires: Sun, 1 Jan 2006 01:00:00 GMT
    D/OkHttp: Pragma: no-cache
    D/OkHttp: Cache-Control: must-revalidate, no-cache, private
    D/OkHttp: Set-Cookie: bid=D6UtQR5N9I4; Expires=Sun, 06-Aug-17 14:26:03 GMT; Domain=.douban.com; Path=/
    D/OkHttp: X-DOUBAN-NEWBID: D6UtQR5N9I4
    D/OkHttp: X-DAE-Node: dis17
    D/OkHttp: X-DAE-App: book
    D/OkHttp: Server: dae
    D/OkHttp: <-- END HTTP
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • Body

    打印請求和返回值的頭部和body信息

    <-- 200 OK https://api.douban.com/v2/book/search?q=%E5%B0%8F%E7%8E%8B%E5%AD%90&tag=&start=0&count=3&token=tokenValue (3583ms)
    D/OkHttp: Connection: keep-alive
    D/OkHttp: Date: Sat, 06 Aug 2016 14:29:11 GMT
    D/OkHttp: Keep-Alive: timeout=30
    D/OkHttp: Content-Type: application/json; charset=utf-8
    D/OkHttp: Vary: Accept-Encoding
    D/OkHttp: Expires: Sun, 1 Jan 2006 01:00:00 GMT
    D/OkHttp: Transfer-Encoding: chunked
    D/OkHttp: Pragma: no-cache
    D/OkHttp: Connection: keep-alive
    D/OkHttp: Cache-Control: must-revalidate, no-cache, private
    D/OkHttp: Keep-Alive: timeout=30
    D/OkHttp: Set-Cookie: bid=ESnahto1_Os; Expires=Sun, 06-Aug-17 14:29:11 GMT; Domain=.douban.com; Path=/
    D/OkHttp: Vary: Accept-Encoding
    D/OkHttp: X-DOUBAN-NEWBID: ESnahto1_Os
    D/OkHttp: Expires: Sun, 1 Jan 2006 01:00:00 GMT
    D/OkHttp: X-DAE-Node: dis5
    D/OkHttp: Pragma: no-cache
    D/OkHttp: X-DAE-App: book
    D/OkHttp: Cache-Control: must-revalidate, no-cache, private
    D/OkHttp: Server: dae
    D/OkHttp: Set-Cookie: bid=5qefVyUZ3KU; Expires=Sun, 06-Aug-17 14:29:11 GMT; Domain=.douban.com; Path=/
    D/OkHttp: X-DOUBAN-NEWBID: 5qefVyUZ3KU
    D/OkHttp: X-DAE-Node: dis17
    D/OkHttp: X-DAE-App: book
    D/OkHttp: Server: dae
    D/OkHttp: {"count":3,"start":0,"total":778,"books":[{"rating":{"max":10,"numRaters":202900,"average":"9.0","min":0},"subtitle":"","author":["[法] 聖埃克蘇佩裏"],"pubdate":"2003-8","tags":[{"count":49322,"name":"小王子","title":"小王子"},{"count":41381,"name":"童話","title":"童話"},{"count":19773,"name":"聖埃克蘇佩裏","title":"聖埃克蘇佩裏"}
    D/OkHttp: <-- END HTTP (13758-byte body)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

3. 爲某個請求設置完整的URL

​ 假如說你的某一個請求不是以base_url開頭該怎麼辦呢?彆着急,辦法很簡單,看下面這個例子你就懂了

public interface BlueService {  
    @GET
    public Call<ResponseBody> profilePicture(@Url String url);
}

Retrofit retrofit = Retrofit.Builder()  
    .baseUrl("https://your.api.url/");
    .build();

BlueService service = retrofit.create(BlueService.class);  
service.profilePicture("https://s3.amazon.com/profile-picture/path");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

​ 直接用@Url註解的方式傳遞完整的url地址即可。

4. 取消請求

Call提供了cancel方法可以取消請求,前提是該請求還沒有執行

String fileUrl = "http://futurestud.io/test.mp4";  
Call<ResponseBody> call =  
    downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {  
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        Log.d(TAG, "request success");
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        if (call.isCanceled()) {
            Log.e(TAG, "request was cancelled");
        } else {
            Log.e(TAG, "other larger issue, i.e. no network connection?");
        }
    }
});
    }

// 觸發某個動作,例如用戶點擊了取消請求的按鈕
call.cancel();  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

四、結語

關於Retrofit常用的方法基本上已經介紹完了,有些請求由於工作保密性的原因,所以就沒有放出來,但是基本的方法和操作都是有的,仿照文中提到的代碼就可以實現你想要的功能。參考了國外的一則系列教程和liangfei的一篇文章圖解 Retrofit - ServiceMethod,由於本人能力有限,有錯誤或者表述不準確的地方還望多多留言指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章