Android Retrofit使用指南,让网络请求更简单。

Retrofit与okhttp都是Square公司的出品,Retrofit是对okhttp做了一层封装,只要简单的配置,就可以是用Retrofit。


github地址:

https://github.com/square/retrofit


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>设置对应的实体类即可返回相应的实体。


猜你喜欢

转载自blog.csdn.net/u012027644/article/details/52382502