Retrofit的基本了解和簡單使用

Retrofit簡介:

一款基于異步線程的網絡請求框架,一款android安全類型的http客戶端,支持線程安全,開發者無需關注線程問題,同樣是基于鏈式編程思想的- 一款網絡請求器。底層集成谷歌自身的Okhttp,它本身不具備http標準網絡訪問基礎,它需要依okhttp進行網絡訪問,另外從Android4.4開始- HttpURLConnection的底層實現采用的是okHttp,最重要的時Retrofit完美支持 Rxjava,這里關于Retrofit的好處不做過多介紹。

官方介紹

一、簡介

Retrofit可將HTTP API轉換為Java接口

public interface GitHubService {@GET("users/{user}/repos")Call<List<Repo>> listRepos(@Path("user") String user);}

Retrofit類生成GitHubService接口的實現。

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();GitHubService service = retrofit.create(GitHubService.class);

每個來自創建GitHub服務的調用都可以向遠程Web服務器發出同步或異步HTTP請求。

Call<List<Repo>> repos = service.listRepos("octocat");

使用注解描述HTTP請求:

*URL支持參數替換和查詢參數

*對象轉換為請求體(例如,JSON,協議緩沖區)

*多部分請求體和文件上傳

二、API聲明

通過接口方法及其參數的注解指導如何處理請求。

請求方法

每個方法必須具有提供請求方法和相對URL的HTTP注解。 有五個內置注解:GET,POST,PUT,DELETE和HEAD。 資源的相對URL在注解中指定。
@GET("users/list")
還可以在URL中指定查詢參數。
@GET("users/list?sort=desc")

網址操作

可以使用替換塊和方法上的參數動態更新請求URL。 替換塊是由{和}包圍的字母數字字符串。 相應的參數必須使用相同的字符串用@Path注解。

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

也可以添加查詢參數。

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

對于復雜的查詢參數組合,可以使用Map。

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

請求主體

可以指定一個帶有@Body對象用作注解的HTTP請求主體。

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

注:該對象也將使用Retrofit實例上指定的轉換器進行轉換。 如果沒有添加轉換器,則只能使用RequestBody。

方法也可以聲明為發送表單編碼和多部分數據。

當方法上存在@FormUrlEncoded時,將發送表單編碼的數據。 每個鍵值對都使用包含名稱的@Field和提供值的對象進行注解。

@FormUrlEncoded@POST("user/edit")Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

當方法上存在@Multipart時,將使用多部分請求。 部分是被聲明使用@Part注解。

@Multipart@PUT("user/photo")Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

多部分使用Retrofit的轉換器,或者它們可以實現RequestBody來處理自己的序列化。

header操作

可以使用@Headers注解為方法設置靜態頭。

@Headers("Cache-Control: max-age=640000")@GET("widget/list")Call<List<Widget>> widgetList();
@Headers({"Accept: application/vnd.github.v3.full+json","User-Agent: Retrofit-Sample-App"})@GET("users/{username}")Call<User> getUser(@Path("username") String username);

請注意,頭不會相互覆蓋。 具有相同名稱的所有頭將包含在請求中。
請求頭可以使用@Header注解動態更新。 必須向@Header提供相應的參數。 如果值為null,則將省略標題。 否則,toString將使用被調用的值做為結果。

@GET("user")Call<User> getUser(@Header("Authorization") String authorization)

頭需要被添加到每個請求中,可被當做一個特定的OkHttp攔截器使用

同步 VS 異步

Call實例可以同步或異步執行。 每個實例只能使用一次,但調用clone()將創建一個可以使用的新實例。
在Android上,回調將在主線程上執行。 在JVM上,回調將發生在執行HTTP請求的同一線程上。

三、Retrofit配置

Retrofit是將API接口轉換為可調用對象的類。 默認情況下,Retrofit將為您的平臺提供正常默認值,但允許自定義。

Converters(轉換器)

默認情況下,Retrofit只能將HTTP主體反序列化為OkHttp的ResponseBody類型,并且它只能接受@Body的RequestBody類型
但是添加Converters可以支持其他類型,六個同級模塊適應流行的序列化庫,為您提供方便。
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml

下面是一個使用GsonConverterFactory類來生成GitHubService接口的實現的示例,該接口使用Gson進行反序列化。

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com").addConverterFactory(GsonConverterFactory.create()).build();
GitHubService service = retrofit.create(GitHubService.class);

自定義轉換器

如果您需要與使用Retrofit不支持模型即用的內容格式(例如YAML,txt,自定義格式)的API進行通信,或者您希望使用其他庫來實現現有格式,則可以輕松創建 你自己的轉換器。 創建一個擴展Converter.Factory類的類,并在構建適配器時傳遞實例。

支持Retrofit需要至少Java 7或Android 2.3。

如果在項目中使用Proguard(混淆),請在配置中添加以下行:

# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions

Retrofit API

使用聲明:

Retrofit1.X與Retrofot2.X在初始化,網絡請求、回調等有較大差異,本文是基于
Retrofit2.X。

1.添加依賴

    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'

備注:這里Retrofit2的各個版本號必須一致

2.創建Retrofit回調的接口

public interface WeatherApi {
    @GET("/microservice/weather?citypinyin=beijing")
    Call<WeatherBean> getWeather();
}

備注:@GET里面的是baseUrl的后綴,用于拼接完整的Url

3.初始化Retrofit實例

        String baseUrl = "http://apistore.baidu.com/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

4.用Retrofit創建接口的代理對象,操作接口方法

        WeatherApi weatherApi = retrofit.create(WeatherApi.class);
        Call<WeatherBean> weatherCall = weatherApi.getWeather();

備注:步驟3中的addConverterFactory(GsonConverterFactory.create())是對于
Call<T>中T的轉換, 默認是Call<ResponseBody>轉化成你自己的Call<Poju>

5.執行回調獲取數據(同步/異步--execute/enqueue)

weatherCall.enqueue(new Callback<WeatherBean>() {
            @Override
            public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response) {
                String weather = response.body().retData.weather;
                tv.setText(weather);
            }

            @Override
            public void onFailure(Call<WeatherBean> call, Throwable t) {

            }
        });

此篇簡單介紹了Retrofit的簡介和基本使用,下一篇會介紹對其接口中注解的理
解以及配合Okhttp實現網絡響應信息攔截
代碼托管地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容