1. 程式人生 > >Android Retrofit使用指南,讓網路請求更簡單。

Android Retrofit使用指南,讓網路請求更簡單。

Retrofit與okhttp都是Square公司的出品,Retrofit是對okhttp做了一層封裝,只要簡單的配置,就可以是用Retrofit。

github地址:

Gradle依賴:

compile 'com.squareup.retrofit2:retrofit:2.1.0'

注意,不支援android2.3以下的版本

以下,我們用apistore的查詢IP地址的介面為例項演示如何使用Retrofit

http://apis.baidu.com/apistore/iplookupservice/iplookup

首先建立一個Http Api介面

public interface GitHubService {
        @Headers("apikey:20c017da573af76f99f90e21fea43062")
        @GET("iplookupservice/iplookup")
        Call<String> getRes(@Query("ip") String ip);
    }

接口裡的每一個方法都必須有註解提供對應請求的方法和URL地址,例如@GET和@POST分別代表使用get和post的方式發起http請求,@Headers註解表示為請求新增一個Header,其他的註解還有@PUT和@DELETE,一個內建了這五種註解。

Call<T>代表返回資料的型別,這裡我們返回的是String型別,也可以返回其他型別。

@Query註解請求引數的名稱。以下為請求引數傳入的幾種示例:

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

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

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

接著我們需要建立一個Retrofit類:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://apis.baidu.com/apistore/")
                //增加返回值為String的支援
                .addConverterFactory(ScalarsConverterFactory.create())
                //增加返回值為Gson的支援
                .addConverterFactory(GsonConverterFactory.create())
                .build();

注意,這裡addConverterFactory()方法為新增對返回資料型別的支援,同時要新增資料型別的依賴項,具體支援的型別如下:
  • Gsoncom.squareup.retrofit2:converter-gson
  • Jacksoncom.squareup.retrofit2:converter-jackson
  • Moshicom.squareup.retrofit2:converter-moshi
  • Protobufcom.squareup.retrofit2:converter-protobuf
  • Wirecom.squareup.retrofit2:converter-wire
  • Simple XMLcom.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

例如,這裡使用到String 和 Gson型別的返回值,則需要新增依賴項:

compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

注意一點這裡返回值的版本需要和Retrofit的版本一致。

接著建立一個剛才我們建立的介面的物件,並得到一個Call物件:

GitHubService service = retrofit.create(GitHubService.class);
        Call<String> getString = service.getRes("211.157.182.19");//引數為發起請求攜帶的引數
然後我們就可以發起請求了:
getString.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.v("retrofitJoe","ok:"+response.body().toString());
            }

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

            }
        });

如果返回的是JSON型別的資料時,Call<T>設定對應的實體類即可返回相應的實體。