Retrofit用法詳解

是Square公司開發(fā)的一款針對Android網(wǎng)絡(luò)請求的框架,Retrofit2底層基于OkHttp實現(xiàn)的,現(xiàn)在已經(jīng)得到Google官方認(rèn)可,大量的app都采用OkHttp做網(wǎng)絡(luò)請求,其源碼詳見[OkHttp Github]。

一、首先先來看一個完整Get請求是如何實現(xiàn):

1、創(chuàng)建業(yè)務(wù)請求接口,具體代碼如下:

   public interface ApiService {
           @GET("book/search")
            Call<BookSearch> getSearchBooks(@Query("name") String name);
    }

** 這里需要稍作說明,@GET注解就表示get請求,@Query表示請求參數(shù),將會以key=value的方式拼接在url后面

2、需要創(chuàng)建一個Retrofit的示例,并完成相應(yīng)的配置

    Retrofit retrofit = new Retrofit.Builder()
           .baseUrl(UrisServerDefine.API_BASE_URL)
           .addConverterFactory(GsonConverterFactory.create())
           .build();
    ApiService service = retrofit.create(ApiService.class);

**這里的baseUrl就是網(wǎng)絡(luò)請求URL相對固定的地址,一般包括請求協(xié)議(如Http)、域名或IP地址、端口號等,當(dāng)然還會有很多其他的配置,下文會詳細(xì)介紹。還有addConverterFactory方法表示需要用什么轉(zhuǎn)換器來解析返回值,GsonConverterFactory.create()表示調(diào)用Gson庫來解析json返回值,具體的下文還會做詳細(xì)介紹。

3、調(diào)用請求方法,并得到Call實例

        Call<BookSearch> call = service.getSearchBooks("小王子");

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

1、同步請求

          BookSearch response = call.execute().body();

**這里需要注意的是網(wǎng)絡(luò)請求一定要在子線程中完成,不能直接在UI線程執(zhí)行,不然會crash

2、異步請求

call.enqueue(new Callback<BookSearch>() {
    @Override
    public void onResponse(Call<BookSearch> call,Response<BookSearch> response) {
        asyncText.setText("異步請求結(jié)果: " + response.body().books.get(0).altTitle);
    }
    @Override
    public void onFailure(Call<BookSearchResponse> call, Throwable t){
        }
 });

二、如何使用

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

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

**引入完第三包接下來就可以使用Retrofit來進(jìn)行網(wǎng)絡(luò)請求了。接下來會對不同的請求方式做進(jìn)一步的說明。
Get 方法

  1. @Query
    Get方法請求參數(shù)都會以key=value的方式拼接在url后面,Retrofit提供了兩種方式設(shè)置請求參數(shù)。第一種就是像上文提到的直接在interface中添加@Query注解,還有一種方式是通過Interceptor實現(xiàn),直接看如何通過Interceptor實現(xiàn)請求參數(shù)的添加。
  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);
          }
   }

addQueryParameter就是添加請求參數(shù)的具體代碼,這種方式比較適用于所有的請求都需要添加的參數(shù),一般現(xiàn)在的網(wǎng)絡(luò)請求都會添加token作為用戶標(biāo)識,那么這種方式就比較適合。
創(chuàng)建完成自定義的Interceptor后,還需要在Retrofit創(chuàng)建client處完成添加。

1 addInterceptor(new CustomInterceptor())

  1. @QueryMap
    如果Query參數(shù)比較多,那么可以通過@QueryMap方式將所有的參數(shù)集成在一個Map統(tǒng)一傳遞,還以上文中的get請求方法為例

    public interface ApiService {
           @GET("book/search")
           Call<BookSearchResponse> getSearchBooks(@QueryMap 
           Map<String, String> options);
    }
    

    調(diào)用的時候?qū)⑺械膮?shù)集合在統(tǒng)一的map中即可

      Map<String, String> options = new HashMap<>();
      map.put("name", "小王子");
      Call<BookSearch> call = service.getSearchBooks(options);
    

    調(diào)用的時候?qū)⑺械膮?shù)集合在統(tǒng)一的map中即可

      Map<String, String> options = new HashMap<>();
      map.put("name", "小王子");
      Call<BookSearch> call = service.getSearchBooks(options);
    
  2. Query集合
    假如你需要添加相同Key值,但是value卻有多個的情況,一種方式是
    添加多個@Query參數(shù),還有一種簡便的方式是將所有的value放置在
    列表中,然后在同一個@Query下完成添加,實例代碼如下:

     public interface ApiService {
           @GET("book/search")
           Call<BookSearch> getSearchBooks(@Query("name") 
           List<String> name);
    }
    
  3. Query非必填
    如果請求參數(shù)為非必填,也就是說即使不傳該參數(shù),服務(wù)端也可以正 常解析,那么如何實現(xiàn)呢?其實也很簡單,請求方法定義處還是需要完整的Query注解,某次請求如果不需要傳該參數(shù)的話,只需填充null即可。針對文章開頭提到的get的請求,加入按以下方式調(diào)用

     Call<BookSearch> call = service.getSearchBooks("小王子");
    
  4. @Path
    如果請求的相對地址也是需要調(diào)用方傳遞,那么可以使用@Path注解,示例代碼如下:

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

    業(yè)務(wù)方想要在地址后面拼接書籍id,那么通過Path注解可以在具體的調(diào)用場景中動態(tài)傳遞,具體的調(diào)用方式如下:

         Call<BookResponse> call =service.getBook("1003078");
    

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

    Post請求

    1. @field
      Post請求需要把請求參數(shù)放置在請求體中,而非拼接在url后面,先來看一個簡單的例子

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

    這里有幾點需要說明的
    @FormUrlEncoded將會自動將請求參數(shù)的類型調(diào)整為application/x-www-form-urlencoded,假如content傳遞的參數(shù)為Good Luck,那么最后得到的請求體就是 content=Good+Luck

      FormUrlEncoded不能用于Get請求
    

    @Field注解將每一個請求參數(shù)都存放至請求體中,還可以添加encoded參數(shù),該參數(shù)為boolean型,具體的用法為

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

    encoded參數(shù)為true的話,key-value-pair將會被編碼,即將中文和特殊字符進(jìn)行編碼轉(zhuǎn)換

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

        @FormUrlEncoded
        @POST("book/reviews")
        Call<String> addReviews(@FieldMap Map<String, String> fields);
      
    2. @Body
      如果Post請求參數(shù)有多個,那么統(tǒng)一封裝到類中應(yīng)該會更好,這樣維護(hù)起來會非常方便

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

      其他請求方式
      除了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);
      

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

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

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

       Uri file1Uri = ... // 從文件選擇器或者攝像頭中獲取 
       Uri file2Uri = ... 
      
       // 創(chuàng)建上傳的service實例
        FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
      
       // 創(chuàng)建文件的part (photo, video, ...)
        MultipartBody.Part body1 = prepareFilePart("video", file1Uri);  
        MultipartBody.Part body2 = prepareFilePart("thumbnail", file2Uri);
      
       // 添加其他的part
       RequestBody description = createPartFromString("hello, this is description speaking");
       // 最后執(zhí)行異步請求操作
       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. 添加自定義的header
      Retrofit提供了兩個方式定義Http請求頭參數(shù):靜態(tài)方法和動態(tài)方法,靜態(tài)方法不能隨不同的請求進(jìn)行變化,頭部信息在初始化的時候就固定了。而動態(tài)方法則必須為每個請求都要單獨設(shè)置。

      靜態(tài)方法

       public interface ApiService {
           @Headers("Cache-Control: max-age=640000")
           @GET("book/search")
           Call<BookSearch> getSearchBooks(@Query("name") String     name);
        }
      

      當(dāng)然你想添加多個header參數(shù)也是可以的,寫法也很簡單

       public interface ApiService {
            @Headers("Accept: application/vnd.yourapi.v1.full+json", "User-Agent: Your-App-Name })
            @GET("book/search")
            Call<BookSearch> getSearchBooks(@Query("name") String name);
        }
      

      此外也可以通過Interceptor來定義靜態(tài)請求頭

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

      添加header參數(shù)Request提供了兩個方法,一個是header(key, value),另一個是.addHeader(key, value),兩者的區(qū)別是,header()如果有重名的將會覆蓋,而addHeader()允許相同key值的header存在然后在OkHttp創(chuàng)建Client實例時,添加RequestInterceptor即可

      private static OkHttpClient getNewClient(){
            return new OkHttpClient.Builder()
           .addInterceptor(new RequestInterceptor())
           .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
          .build();
      }
      

      動態(tài)方法

       public interface ApiService {
            @GET("book/search")
            Call<BookSearch> getSearchBooks(
            @Header("Content-Range") String contentRange, 
            @Query("name") String name);
      }
      
      1. 網(wǎng)絡(luò)請求日志
        調(diào)試網(wǎng)絡(luò)請求的時候經(jīng)常需要關(guān)注一下請求參數(shù)和返回值,以便判斷和定位問題出在哪里,Retrofit官方提供了一個很方便查看日志的Interceptor,你可以控制你需要的打印信息類型,使用方法也很簡單。
        首先需要在build.gradle文件中引入logging-interceptor

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

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

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

        HttpLoggingInterceptor提供了4中控制打印信息類型的等級,分別是NONE,BASIC,HEADERS,BODY,接下來分別來說一下相應(yīng)的打印信息類型。
        NONE
        沒有任何日志信息
        Basic
        打印請求類型,URL,請求體大小,返回值狀態(tài)以及返回值的大小

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

        Headers
        打印返回請求和返回值的頭部信息,請求類型,URL以及返回值狀態(tài)碼

          <-- 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
        

        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":["[法] 圣??颂K佩里"],"pubdate":"2003-8","tags":[{"count":49322,"name":"小王子","title":"小王子"},{"count":41381,"name":"童話","title":"童話"},{"count":19773,"name":"圣??颂K佩里","title":"圣??颂K佩里"}
             D/OkHttp: <-- END HTTP (13758-byte body)
        
      2. 為某個請求設(shè)置完整的URL
        假如說你的某一個請求不是以base_url開頭該怎么辦呢?別著急,辦法很簡單,看下面這個例子你就懂了

         public interface ApiService {  
                @GET
                public Call<ResponseBody> profilePicture(@Url String url);
        }
        
              Retrofit retrofit = Retrofit.Builder()  
              .baseUrl("https://your.api.url/");
              .build();
        
          ApiService service = retrofit.create(ApiService.class);  
          service.profilePicture("https://s3.amazon.com/profile-picture/path")
        

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

        4. 取消請求
        Call提供了cancel方法可以取消請求,前提是該請求還沒有執(zhí)行

          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?");
              }
             }
           });
        }
        
              // 觸發(fā)某個動作,例如用戶點擊了取消請求的按鈕
                call.cancel();  
          }
        
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Retrofit用法詳解 一、簡介 Retrofit是Square公司開發(fā)的一款針對Android網(wǎng)絡(luò)請求的框架,...
    流水潺湲閱讀 1,482評論 0 6
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,715評論 19 139
  • Retrofit Retrofit是Square公司開發(fā)的一款針對Android網(wǎng)絡(luò)請求的框架,Retrofit2...
    Reathin閱讀 1,832評論 1 11
  • 百人計劃過半,就算沒有要求,也是時候做一次總結(jié),做一次回顧。 當(dāng)初報名的時候自己的想法是,做一個改變,這個改變最多...
    醒卯閱讀 274評論 0 0
  • 題目2 : Composition 時間限制:10000ms 單點時限:1000ms 內(nèi)存限制:256MB 描述A...

友情鏈接更多精彩內(nèi)容