Retrofit是一套RESTful架構的Android(Java)客戶端實現,基於註解,提供JSON to POJO(Plain Ordinary Java Object,簡單Java對象),POJO to JSON,網絡請求(POST,GET,PUT,DELETE等)封裝。用官方本身的介紹就是:java
A type-safe REST client for Android and Javaandroid
現已更新到2.0的版本,與1.0版本的使用上仍是不小的差異,我也是第一次用,這裏主要和你們研究研究2.0版本簡單使用。也可參詳官方示例。
git
首先添加網絡請求權限github
<uses-permission android:name="android.permission.INTERNET"/>複製代碼
Retrofit2.0版本後只支持okhttp請求,也已經封裝好了,就不須要添加okhttp的依賴了。json
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
}複製代碼
接下來瞧一瞧Retrofit初始化以及如何請求數據。api
public static final String BASE_URL = "https://api.github.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();複製代碼
BASE_URL就是你請求的Server地址。網絡
.addConverterFactory(GsonConverterFactory.create())複製代碼
Retrofit2.0不提供返回JSON數據的默認解析方式,須要手動指定,支持Jackson等多種解析方式。須要哪一種就添加相應的依賴,這裏添加的是Retrofit提供的converter-gson依賴。有點不爽的就是不支持FastJson解析,有須要的話能夠本身寫一個FastjsonConverterFactory繼承Converter.Factory實現。
雖然Retrofit2.0後只支持okhttp請求,但你也能夠自定義一個okhttp再配置進Retrofit。架構
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// Do anything with response here
return response;
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
});複製代碼
實現轉換HTTP API爲Java接口,Retrofit提供了5種內置的註解:GET、POST、PUT、DELETE和HEAD,在註解中指定的資源的相對URL。框架
public interface NetWorkService {
@GET("users/basil2style")
Call<DataBean> getData();
}複製代碼
使用替換塊和參數進行動態更新,替換塊是{ and }包圍的字母數字組成的字符串,相應的參數必須使用相同的字符串被@Path進行註釋。異步
@GET("repos/{params1}/{params2}/contributors")
Call<List<DataBean2>> getData(
@Path("params1") String params1,
@Path("params2") String params2,
);複製代碼
當咱們調用getData()這個方法的時候,Retrofit會建立這個URL。若是咱們傳入Square和Retrofit字符串,分別做爲owner和repo參數。咱們就會獲得這個URL:api.github.com/repos/squar…
添加查詢參數
@GET("repos/square/{retrofit}/contributors")
Call<List<DataBean2>> groupData(@Path("retrofit") String retrofit, @Query("sort") String sort);複製代碼
當咱們調用getData()方法時,傳入一個查詢參數字符串"ok",這樣咱們就能獲得URL:api.github.com/repos/squar…
固然若是查詢參數過多,咱們也可使用Map進行組合再傳進來。
@GET("repos/square/{retrofit}/contributors")
Call<List<DataBean2>> getData(@Path("repos") String repos, @QueryMap Map<String, String> parameters);複製代碼
Retrifot支持同步和異步的請求方式,先使用Retrofit類生成接口NetWorkService的實現。
NetWorkService service = retrofit.create(NetWorkService.class);複製代碼
Call<DataBean> call = service.getData(Square,Retrofit);
DataBean bean = call.execute().body();複製代碼
注意同步請求不可在主線程執行,你懂得。且call只能執行execute()方法一次,若要再次請求可經過Call<DataBean> call = call.clone()
來再複製一個Call對象。
call.enqueue(new Callback<DataBean>() {
@Override
public void onResponse(Call<DataBean> call, Response<DataBean> response) {
Toast.makeText(MainActivity.this, "請求成功", Toast.LENGTH_SHORT).show();
DataBean bean = response.body();
tvMain.setText(bean.toString());
}
@Override
public void onFailure(Call<DataBean> call, Throwable t) {
}
});複製代碼
當咱們執行的同步或異步加入隊列後,能夠隨時使用call.cancel()方法取消請求。
註解中參數的寫法與BASE_URL的拼接必定要注意,請看如下寫法。
BASE_URL:api.github.com/repos/squar…
Get註解: @GET("/basil2style")
結果URL: api.github.com/basil2style
BASE_URL:api.github.com/repos/squar…
Get註解: @GET("basil2style")
結果URL: api.github.com/repos/basil…
BASE_URL:api.github.com/repos/squar…
Get註解: @GET("basil2style")
結果URL: api.github.com/repos/squar…
Retrofit2.0的基本實現講解完畢,Retrofit+Okhttp+Gson能夠算是目前來講至關快的超級網絡請求框架了。相比較於Volley都快很多,親測結果很爽。小夥伴們趕忙整起來吧!
技術渣一枚,有寫的不對的地方歡迎大神們留言指正,有什麼疑惑或者不懂的地方也能夠在我Github上Retrofit2Demo項目的Issues中提出,我會及時解答。附上Retrofit2Demo的地址:
Retrofit2Demo