這是一份很詳細的 Retrofit 2.0 使用教程(含實例講解)(轉)

前言

  • Andrroid開發中,網絡請求十分經常使用
  • 而在Android網絡請求庫中,Retrofit是當下最熱的一個網絡請求庫

Github截圖

  • 今天,我將獻上一份很是詳細Retrofit v2.0的使用教程,但願大家會喜歡。

若是對Retrofit v2.0的源碼感興趣,可看文章:Android:手把手帶你深刻剖析 Retrofit 2.0 源碼php


目錄

目錄


1. 簡介

Retrofit簡介

特別注意:java

  • 準確來講,Retrofit 是一個 RESTful 的 HTTP 網絡請求框架的封裝。
  • 緣由:網絡請求的工做本質上是 OkHttp 完成,而 Retrofit 僅負責 網絡請求接口的封裝

本質過程

  • App應用程序經過 Retrofit 請求網絡,其實是使用 Retrofit 接口層封裝請求參數、Header、Url 等信息,以後由 OkHttp 完成後續的請求操做
  • 在服務端返回數據以後,OkHttp 將原始的結果交給 Retrofit,Retrofit根據用戶的需求對結果進行解析

2. 與其餘開源請求庫對比

除了Retrofit,現在Android中主流的網絡請求框架有:android

  • Android-Async-Http
  • Volley
  • OkHttp

下面是簡單介紹:git

網絡請求加載 - 介紹

一圖讓你瞭解所有的網絡請求庫和他們之間的區別!github

網絡請求庫 - 對比


附:各個主流網絡請求庫的Github地址ajax


3. 使用介紹

使用 Retrofit 的步驟共有7個:json

步驟1:添加Retrofit庫的依賴 
步驟2:建立 接收服務器返回數據 的類 
步驟3:建立 用於描述網絡請求 的接口 
步驟4:建立 Retrofit 實例 
步驟5:建立 網絡請求接口實例 並 配置網絡請求參數 
步驟6:發送網絡請求(異步 / 同步)api

封裝了 數據轉換、線程切換的操做服務器

步驟7: 處理服務器返回的數據網絡

接下來,咱們一步步進行講解。

步驟1:添加Retrofit庫的依賴

1. 在 Gradle加入Retrofit庫的依賴

因爲Retrofit是基於OkHttp,因此還須要添加OkHttp庫依賴

build.gradle

1 dependencies {
2     compile 'com.squareup.retrofit2:retrofit:2.0.2'
3     // Retrofit庫
4     compile 'com.squareup.okhttp3:okhttp:3.1.2'
5     // Okhttp庫
6   }

 

2. 添加 網絡權限 
AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

 

步驟2:建立 接收服務器返回數據 的類

Reception.java

1 public class Reception {
2     ...
3     // 根據返回數據的格式和數據解析方式(Json、XML等)定義
4     // 下面會在實例進行說明
5         }

 

步驟3:建立 用於描述網絡請求 的接口

  • Retrofit將 Http請求 抽象成 Java接口:採用 註解 描述網絡請求參數 和配置網絡請求參數 
    1. 用 動態代理 動態 將該接口的註解「翻譯」成一個 Http 請求,最後再執行 Http 請求 
    2. 注:接口中的每一個方法的參數都須要使用註解標註,不然會報錯


GetRequest_Interface.interface

 1 public interface GetRequest_Interface {
 2 
 3     @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
 4     Call<Translation>  getCall();
 5     // @GET註解的做用:採用Get方法發送網絡請求
 6 
 7     // getCall() = 接收網絡請求數據的方法
 8     // 其中返回類型爲Call<*>,*是接收數據的類(即上面定義的Translation類)
 9     // 若是想直接得到Responsebody中的內容,能夠定義網絡請求返回值爲Call<ResponseBody>
10 }

 

下面詳細介紹Retrofit 網絡請求接口 的註解類型。

註解類型

註解類型

註解說明

第一類:網絡請求方法

網絡請求方法註解

詳細說明: 
a. @GET、@POST、@PUT、@DELETE、@HEAD 
以上方法分別對應 HTTP中的網絡請求方式

1 public interface GetRequest_Interface {
2 
3     @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
4     Call<Translation>  getCall();
5     // @GET註解的做用:採用Get方法發送網絡請求
6     // getCall() = 接收網絡請求數據的方法
7     // 其中返回類型爲Call<*>,*是接收數據的類(即上面定義的Translation類)
8 }

 

此處特地說明URL的組成:Retrofit把 網絡請求的URL 分紅了兩部分設置:

 1 // 第1部分:在網絡請求接口的註解設置
 2  @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
 3 Call<Translation>  getCall();
 4 
 5 // 第2部分:在建立Retrofit實例時經過.baseUrl()設置
 6 Retrofit retrofit = new Retrofit.Builder()
 7                 .baseUrl("http://fanyi.youdao.com/") //設置網絡請求的Url地址
 8                 .addConverterFactory(GsonConverterFactory.create()) //設置數據解析器
 9                 .build();
10 
11 // 從上面看出:一個請求的URL能夠經過 替換塊 和 請求方法的參數 來進行動態的URL更新。
12 // 替換塊是由 被{}包裹起來的字符串構成
13 // 即:Retrofit支持動態改變網絡請求根目錄

 

  • 網絡請求的完整 Url =在建立Retrofit實例時經過.baseUrl()設置 +網絡請求接口的註解設置(下面稱 「path「 )
  • 具體整合的規則以下:

URL整合規則

建議採用第三種方式來配置,並儘可能使用同一種路徑形式。

b. @HTTP

  • 做用:替換@GET、@POST、@PUT、@DELETE、@HEAD註解的做用 及 更多功能拓展
  • 具體使用:經過屬性method、path、hasBody進行設置
 1 public interface GetRequest_Interface {
 2     /**
 3      * method:網絡請求的方法(區分大小寫)
 4      * path:網絡請求地址路徑
 5      * hasBody:是否有請求體
 6      */
 7     @HTTP(method = "GET", path = "blog/{id}", hasBody = false)
 8     Call<ResponseBody> getCall(@Path("id") int id);
 9     // {id} 表示是一個變量
10     // method 的值 retrofit 不會作處理,因此要自行保證準確
11 }

 

第二類:標記

標記類註解

a. @FormUrlEncoded

  • 做用:表示發送form-encoded的數據

每一個鍵值對須要用@Filed來註解鍵名,隨後的對象須要提供值。

b. @Multipart

 

 

  • 做用:表示發送form-encoded的數據(適用於 有文件 上傳的場景) 

 

每一個鍵值對須要用@Part來註解鍵名,隨後的對象須要提供值。 
具體使用以下: 
GetRequest_Interface

 1 public interface GetRequest_Interface {
 2         /**
 3          *代表是一個表單格式的請求(Content-Type:application/x-www-form-urlencoded)
 4          * <code>Field("username")</code> 表示將後面的 <code>String name</code> 中name的取值做爲 username 的值
 5          */
 6         @POST("/form")
 7         @FormUrlEncoded
 8         Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
 9 
10         /**
11          * {@link Part} 後面支持三種類型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意類型
12          * 除 {@link okhttp3.MultipartBody.Part} 之外,其它類型都必須帶上表單字段({@link okhttp3.MultipartBody.Part} 中已經包含了表單字段的信息),
13          */
14         @POST("/form")
15         @Multipart
16         Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
17 
18 }
19 
20 // 具體使用
21        GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
22         // @FormUrlEncoded 
23         Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);
24 
25         //  @Multipart
26         RequestBody name = RequestBody.create(textType, "Carson");
27         RequestBody age = RequestBody.create(textType, "24");
28 
29         MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
30         Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);

 

第三類:網絡請求參數

網絡請求參數註解

詳細說明

a. @Header & @Headers

  • 做用:添加請求頭 &添加不固定的請求頭
  • 具體使用以下:
 1 // @Header
 2 @GET("user")
 3 Call<User> getUser(@Header("Authorization") String authorization)
 4 
 5 // @Headers
 6 @Headers("Authorization: authorization")
 7 @GET("user")
 8 Call<User> getUser()
 9 
10 // 以上的效果是一致的。
11 // 區別在於使用場景和使用方式
12 // 1. 使用場景:@Header用於添加不固定的請求頭,@Headers用於添加固定的請求頭
13 // 2. 使用方式:@Header做用於方法的參數;@Headers做用於方法

 

b. @Body

 

 

  • 做用:以 Post方式 傳遞 自定義數據類型 給服務器
  • 特別注意:若是提交的是一個Map,那麼做用至關於 @Field 

 

不過Map要通過 FormBody.Builder 類處理成爲符合 Okhttp 格式的表單,如:

1 FormBody.Builder builder = new FormBody.Builder();
2 builder.add("key","value");

c. @Field & @FieldMap

  • 做用:發送 Post請求 時提交請求的表單字段
  • 具體使用:與 @FormUrlEncoded 註解配合使用
 1 public interface GetRequest_Interface {
 2         /**
 3          *代表是一個表單格式的請求(Content-Type:application/x-www-form-urlencoded)
 4          * <code>Field("username")</code> 表示將後面的 <code>String name</code> 中name的取值做爲 username 的值
 5          */
 6         @POST("/form")
 7         @FormUrlEncoded
 8         Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
 9 
10 /**
11          * Map的key做爲表單的鍵
12          */
13         @POST("/form")
14         @FormUrlEncoded
15         Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);
16 
17 }
18 
19 // 具體使用
20          // @Field
21         Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);
22 
23         // @FieldMap
24         // 實現的效果與上面相同,但要傳入Map
25         Map<String, Object> map = new HashMap<>();
26         map.put("username", "Carson");
27         map.put("age", 24);
28         Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);

 

d. @Part & @PartMap

  • 做用:發送 Post請求 時提交請求的表單字段

    與@Field的區別:功能相同,但攜帶的參數類型更加豐富,包括數據流,因此適用於 有文件上傳 的場景

  • 具體使用:與 @Multipart 註解配合使用

 1 public interface GetRequest_Interface {
 2 
 3           /**
 4          * {@link Part} 後面支持三種類型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意類型
 5          * 除 {@link okhttp3.MultipartBody.Part} 之外,其它類型都必須帶上表單字段({@link okhttp3.MultipartBody.Part} 中已經包含了表單字段的信息),
 6          */
 7         @POST("/form")
 8         @Multipart
 9         Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
10 
11         /**
12          * PartMap 註解支持一個Map做爲參數,支持 {@link RequestBody } 類型,
13          * 若是有其它的類型,會被{@link retrofit2.Converter}轉換,如後面會介紹的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter}
14          * 因此{@link MultipartBody.Part} 就不適用了,因此文件只能用<b> @Part MultipartBody.Part </b>
15          */
16         @POST("/form")
17         @Multipart
18         Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file);
19 
20         @POST("/form")
21         @Multipart
22         Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args);
23 }
24 
25 // 具體使用
26  MediaType textType = MediaType.parse("text/plain");
27         RequestBody name = RequestBody.create(textType, "Carson");
28         RequestBody age = RequestBody.create(textType, "24");
29         RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "這裏是模擬文件的內容");
30 
31         // @Part
32         MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
33         Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
34         ResponseBodyPrinter.printResponseBody(call3);
35 
36         // @PartMap
37         // 實現和上面一樣的效果
38         Map<String, RequestBody> fileUpload2Args = new HashMap<>();
39         fileUpload2Args.put("name", name);
40         fileUpload2Args.put("age", age);
41         //這裏並不會被當成文件,由於沒有文件名(包含在Content-Disposition請求頭中),但上面的 filePart 有
42         //fileUpload2Args.put("file", file);
43         Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //單獨處理文件
44         ResponseBodyPrinter.printResponseBody(call4);
45 }

 

e. @Query和@QueryMap

  • 做用:用於 @GET 方法的查詢參數(Query = Url 中 ‘?’ 後面的 key-value)

    如:url = http://www.println.net/?cate=android,其中,Query = cate

  • 具體使用:配置時只須要在接口方法中增長一個參數便可:

1    @GET("/")    
2    Call<String> cate(@Query("cate") String cate);
3 }
4 
5 // 其使用方式同 @Field與@FieldMap,這裏不做過多描述

 

f. @Path

  • 做用:URL地址的缺省值
  • 具體使用:
1 public interface GetRequest_Interface {
2 
3         @GET("users/{user}/repos")
4         Call<ResponseBody>  getBlog(@Path("user") String user );
5         // 訪問的API是:https://api.github.com/users/{user}/repos
6         // 在發起請求時, {user} 會被替換爲方法的第一個參數 user(被@Path註解做用)
7     }

 

g. @Url

  • 做用:直接傳入一個請求的 URL變量 用於URL設置
  • 具體使用:
1 public interface GetRequest_Interface {
2 
3         @GET
4         Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
5        // 當有URL註解時,@GET傳入的URL就能夠省略
6        // 當GET、POST...HTTP等方法中沒有設置Url時,則必須使用 {@link Url}提供
7 
8 }

 

彙總

彙總

步驟4:建立 Retrofit 實例

1  Retrofit retrofit = new Retrofit.Builder()
2                 .baseUrl("http://fanyi.youdao.com/") // 設置網絡請求的Url地址
3                 .addConverterFactory(GsonConverterFactory.create()) // 設置數據解析器
4                 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺
5                 .build();

 

a. 關於數據解析器(Converter)

  • Retrofit支持多種數據解析方式
  • 使用時須要在Gradle添加依賴
數據解析器 Gradle依賴
Gson com.squareup.retrofit2:converter-gson:2.0.2
Jackson com.squareup.retrofit2:converter-jackson:2.0.2
Simple XML com.squareup.retrofit2:converter-simplexml:2.0.2
Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2
Moshi com.squareup.retrofit2:converter-moshi:2.0.2
Wire com.squareup.retrofit2:converter-wire:2.0.2
Scalars com.squareup.retrofit2:converter-scalars:2.0.2

b. 關於網絡請求適配器(CallAdapter)

  • Retrofit支持多種網絡請求適配器方式:guava、Java8和rxjava 

    使用時如使用的是 Android 默認的 CallAdapter,則不須要添加網絡請求適配器的依賴,不然則須要按照需求進行添加 
    Retrofit 提供的 CallAdapter

  • 使用時須要在Gradle添加依賴:
網絡請求適配器 Gradle依賴
guava com.squareup.retrofit2:adapter-guava:2.0.2
Java8 com.squareup.retrofit2:adapter-java8:2.0.2
rxjava com.squareup.retrofit2:adapter-rxjava:2.0.2

步驟5:建立 網絡請求接口實例

1    // 建立 網絡請求接口 的實例
2         GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
3 
4         //對 發送請求 進行封裝
5         Call<Reception> call = request.getCall();

步驟6:發送網絡請求(異步 / 同步)

封裝了 數據轉換、線程切換的操做

 1 //發送網絡請求(異步)
 2         call.enqueue(new Callback<Translation>() {
 3             //請求成功時回調
 4             @Override
 5             public void onResponse(Call<Translation> call, Response<Translation> response) {
 6                 //請求處理,輸出結果
 7                 response.body().show();
 8             }
 9 
10             //請求失敗時候的回調
11             @Override
12             public void onFailure(Call<Translation> call, Throwable throwable) {
13                 System.out.println("鏈接失敗");
14             }
15         });
16 
17 // 發送網絡請求(同步)
18 Response<Reception> response = call.execute();

 

步驟7:處理返回數據

經過response類的 body()對返回的數據進行處理

 1 //發送網絡請求(異步)
 2         call.enqueue(new Callback<Translation>() {
 3             //請求成功時回調
 4             @Override
 5             public void onResponse(Call<Translation> call, Response<Translation> response) {
 6                 // 對返回數據進行處理
 7                 response.body().show();
 8             }
 9 
10             //請求失敗時候的回調
11             @Override
12             public void onFailure(Call<Translation> call, Throwable throwable) {
13                 System.out.println("鏈接失敗");
14             }
15         });
16 
17 // 發送網絡請求(同步)
18   Response<Reception> response = call.execute();
19   // 對返回數據進行處理
20   response.body().show();

 


4. 實例講解

接下來,我將用兩個實例分別對 Retrofit GET方式 和 POST方式進行 網絡請求 講解。

4.1 實例1

  • 實現功能:將中文翻譯成英文
  • 實現方案:採用Get方法對 金山詞霸API 發送網絡請求 

    採用 Gson 進行數據解析


金山詞典

  • 步驟說明

步驟1:添加Retrofit庫的依賴 
步驟2:建立 接收服務器返回數據 的類 
步驟3:建立 用於描述網絡請求 的接口 
步驟4:建立 Retrofit 實例 
步驟5:建立 網絡請求接口實例 並 配置網絡請求參數 
步驟6:發送網絡請求(採用最經常使用的異步方式)

封裝了 數據轉換、線程切換的操做

步驟7: 處理服務器返回的數據

接下來,咱們一步步進行講解。

  • 具體使用

步驟1:添加Retrofit庫的依賴

1. 在 Gradle加入Retrofit庫的依賴

因爲Retrofit是基於OkHttp,因此還須要添加OkHttp庫依賴

build.gradle

1 dependencies {
2     compile 'com.squareup.retrofit2:retrofit:2.0.2'
3     // Retrofit庫
4     compile 'com.squareup.okhttp3:okhttp:3.1.2'
5     // Okhttp庫
6   }

 

2. 添加 網絡權限 
AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

 

步驟2:建立 接收服務器返回數據 的類

  • 金山詞霸API 的數據格式說明以下:
 1 // URL模板
 2 http://fy.iciba.com/ajax.php
 3 
 4 // URL實例
 5 http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world
 6 
 7 // 參數說明:
 8 // a:固定值 fy
 9 // f:原文內容類型,日語取 ja,中文取 zh,英語取 en,韓語取 ko,德語取 de,西班牙語取 es,法語取 fr,自動則取 auto
10 // t:譯文內容類型,日語取 ja,中文取 zh,英語取 en,韓語取 ko,德語取 de,西班牙語取 es,法語取 fr,自動則取 auto
11 // w:查詢內容

 

API格式說明

  • 根據 金山詞霸API 的數據格式,建立 接收服務器返回數據 的類:

Translation.java

 1 public class Translation {
 2         private int status;
 3 
 4     private content content;
 5     private static class content {
 6         private String from;
 7         private String to;
 8         private String vendor;
 9         private String out;
10         private int errNo;
11     }
12 
13     //定義 輸出返回數據 的方法
14     public void show() {
15         System.out.println(status);
16 
17         System.out.println(content.from);
18         System.out.println(content.to);
19         System.out.println(content.vendor);
20         System.out.println(content.out);
21         System.out.println(content.errNo);
22     }
23 }

 

步驟3:建立 用於描述網絡請求 的接口

採用 註解 描述 網絡請求參數。 
GetRequest_Interface.java

1 public interface GetRequest_Interface {
2 
3  @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
4     Call<Translation> getCall();
5     // 註解裏傳入 網絡請求 的部分URL地址
6     // Retrofit把網絡請求的URL分紅了兩部分:一部分放在Retrofit對象裏,另外一部分放在網絡請求接口裏
7     // 若是接口裏的url是一個完整的網址,那麼放在Retrofit對象裏的URL能夠忽略
8     // getCall()是接受網絡請求數據的方法
9 }

 

接下來的步驟均在GetRequest.java內實現(看註釋)

步驟4:建立Retrofit對象 
步驟5:建立 網絡請求接口 的實例 
步驟6:發送網絡請求

以最經常使用的 異步請求 爲例

步驟7:處理返回數據

GetRequest.java

 1 public class GetRequest extends AppCompatActivity {
 2 
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7 
 8         request();
 9         // 使用Retrofit封裝的方法
10     }
11     public void request() {
12 
13         //步驟4:建立Retrofit對象
14         Retrofit retrofit = new Retrofit.Builder()
15                 .baseUrl("http://fy.iciba.com/") // 設置 網絡請求 Url
16                 .addConverterFactory(GsonConverterFactory.create()) //設置使用Gson解析(記得加入依賴)
17                 .build();
18 
19         // 步驟5:建立 網絡請求接口 的實例
20         GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
21 
22         //對 發送請求 進行封裝
23         Call<Translation> call = request.getCall();
24 
25         //步驟6:發送網絡請求(異步)
26         call.enqueue(new Callback<Translation>() {
27             //請求成功時回調
28             @Override
29             public void onResponse(Call<Translation> call, Response<Translation> response) {
30                 // 步驟7:處理返回的數據結果
31                 response.body().show();
32             }
33 
34             //請求失敗時回調
35             @Override
36             public void onFailure(Call<Translation> call, Throwable throwable) {
37                 System.out.println("鏈接失敗");
38             }
39         });
40     }
41 }

 

因爲此處採用了 Gson 解析,因此須要在 Gradle加入依賴 
build.gradle

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

運行結果

運行結果

Demo地址

Carson_Ho的Github:https://github.com/Carson-Ho/RetrofitDemo


4.2 實例2

  • 實現的功能:將 英文 翻譯成 中文
  • 實現方法:採用Post方法對 有道API 發送網絡請求 

    採用 Gson 進行數據解析


有道翻譯

  • 使用步驟

步驟1:添加Retrofit庫的依賴 
步驟2:建立 接收服務器返回數據 的類 
步驟3:建立 用於描述網絡請求 的接口 
步驟4:建立 Retrofit 實例 
步驟5:建立 網絡請求接口實例 並 配置網絡請求參數 
步驟6:發送網絡請求(採用最經常使用的異步方式)

封裝了 數據轉換、線程切換的操做

步驟7: 處理服務器返回的數據

接下來,咱們一步步進行Retrofit的使用。

  • 具體使用

步驟1:添加Retrofit庫的依賴

1. 在 Gradle加入Retrofit庫的依賴

因爲Retrofit是基於OkHttp,因此還須要添加OkHttp庫依賴

build.gradle

1 dependencies {
2     compile 'com.squareup.retrofit2:retrofit:2.0.2'
3     // Retrofit庫
4     compile 'com.squareup.okhttp3:okhttp:3.1.2'
5     // Okhttp庫
6   }

 

2. 添加 網絡權限 
AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

 

步驟2:建立 接收服務器返回數據 的類

  • API 的數據格式說明以下:
 1 // URL
 2 http://fanyi.youdao.com/translate
 3 
 4 // URL實例
 5 http://fanyi.youdao.com/translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=
 6 
 7 
 8 // 參數說明
 9 // doctype:json 或 xml
10 // jsonversion:若是 doctype 值是 xml,則去除該值,若 doctype 值是 json,該值爲空便可
11 // xmlVersion:若是 doctype 值是 json,則去除該值,若 doctype 值是 xml,該值爲空便可
12 // type:語言自動檢測時爲 null,爲 null 時可爲空。英譯中爲 EN2ZH_CN,中譯英爲 ZH_CN2EN,日譯中爲 JA2ZH_CN,中譯日爲 ZH_CN2JA,韓譯中爲 KR2ZH_CN,中譯韓爲 ZH_CN2KR,中譯法爲 ZH_CN2FR,法譯中爲 FR2ZH_CN
13 // keyform:mdict. + 版本號 + .手機平臺。可爲空
14 // model:手機型號。可爲空
15 // mid:平臺版本。可爲空
16 // imei:???。可爲空
17 // vendor:應用下載平臺。可爲空
18 // screen:屏幕寬高。可爲空
19 // ssid:用戶名。可爲空
20 // abtest:???。可爲空
21 
22 // 請求方式說明
23 // 請求方式:POST
24 // 請求體:i
25 // 請求格式:x-www-form-urlencoded

 

數據格式說明

  • 根據 有道API 的數據格式,建立 接收服務器返回數據 的類:

Translation.java

 1 public class Translation1 {
 2 
 3     private String type;
 4     private int errorCode;
 5     private int elapsedTime;
 6     private List<List<TranslateResultBean>> translateResult;
 7 
 8     public String getType() {
 9         return type;
10     }
11 
12     public void setType(String type) {
13         this.type = type;
14     }
15 
16     public int getErrorCode() {
17         return errorCode;
18     }
19 
20     public void setErrorCode(int errorCode) {
21         this.errorCode = errorCode;
22     }
23 
24     public int getElapsedTime() {
25         return elapsedTime;
26     }
27 
28     public void setElapsedTime(int elapsedTime) {
29         this.elapsedTime = elapsedTime;
30     }
31 
32     public List<List<TranslateResultBean>> getTranslateResult() {
33         return translateResult;
34     }
35 
36     public void setTranslateResult(List<List<TranslateResultBean>> translateResult) {
37         this.translateResult = translateResult;
38     }
39 
40     public static class TranslateResultBean {
41         /**
42          * src : merry me
43          * tgt : 我快樂
44          */
45 
46         public String src;
47         public String tgt;
48 
49         public String getSrc() {
50             return src;
51         }
52 
53         public void setSrc(String src) {
54             this.src = src;
55         }
56 
57         public String getTgt() {
58             return tgt;
59         }
60 
61         public void setTgt(String tgt) {
62             this.tgt = tgt;
63         }
64     }
65 
66 }

 

步驟3:建立 用於描述網絡請求 的接口

採用 註解 描述 網絡請求參數。

PostRequest_Interface.java

1 public interface PostRequest_Interface {
2 
3     @POST("translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=")
4     @FormUrlEncoded
5     Call<Translation1> getCall(@Field("i") String targetSentence);
6     //採用@Post表示Post方法進行請求(傳入部分url地址)
7     // 採用@FormUrlEncoded註解的緣由:API規定採用請求格式x-www-form-urlencoded,即表單形式
8     // 須要配合@Field 向服務器提交須要的字段
9 }

 

接下來的步驟均在PostRequest.java內實現(看註釋)

步驟4:建立Retrofit對象 
步驟5:建立 網絡請求接口 的實例 
步驟6:發送網絡請求

以最經常使用的 異步請求 爲例

步驟7:處理返回數據

PostRequest.java

 1 public class PostRequest extends AppCompatActivity {
 2 
 3 
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8 
 9         request();
10     }
11     public void request() {
12 
13         //步驟4:建立Retrofit對象
14         Retrofit retrofit = new Retrofit.Builder()
15                 .baseUrl("http://fanyi.youdao.com/") // 設置 網絡請求 Url
16                 .addConverterFactory(GsonConverterFactory.create()) //設置使用Gson解析(記得加入依賴)
17                 .build();
18 
19         // 步驟5:建立 網絡請求接口 的實例
20         PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);
21 
22         //對 發送請求 進行封裝(設置須要翻譯的內容)
23         Call<Translation1> call = request.getCall("I love you");
24 
25         //步驟6:發送網絡請求(異步)
26         call.enqueue(new Callback<Translation1>() {
27 
28             //請求成功時回調
29             @Override
30             public void onResponse(Call<Translation1> call, Response<Translation1> response) {
31                 // 步驟7:處理返回的數據結果:輸出翻譯的內容
32                 System.out.println(response.body().getTranslateResult().get(0).get(0).getTgt());
33             }
34 
35             //請求失敗時回調
36             @Override
37             public void onFailure(Call<Translation1> call, Throwable throwable) {
38                 System.out.println("請求失敗");
39                 System.out.println(throwable.getMessage());
40             }
41         });
42     }
43 
44 
45 }

 

因爲此處採用了 Gson 解析,因此須要在 Gradle 加入依賴 
build.gradle

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

 

運行結果

運行結果

Demo地址

Carson_Ho的Github:https://github.com/Carson-Ho/RetrofitDemo


5. Retrofit 的拓展使用

  • Retrofit的使用場景很是豐富,如支持RxJavaPrototocobuff
  • 具體設置也很是簡單 & 方便:
<-- 主要在建立Retrofit對象中設置 -->
1 Retrofit retrofit = new Retrofit.Builder()
2   .baseUrl(""http://fanyi.youdao.com/"")
3   .addConverterFactory(ProtoConverterFactory.create()) // 支持Prototocobuff解析
4   .addConverterFactory(GsonConverterFactory.create()) // 支持Gson解析
5   .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava
6   .build();
 

具體關於 RxJava的使用這裏就不展開,請期待下篇關於 Rxjava的文章。

 

轉自:http://www.javashuo.com/article/p-tatoxysa-ke.html

相關文章
相關標籤/搜索