Retrofit学习一:文档介绍

Retrofit

官方文档:http://square.github.io/retrofit/

源码和例子,Github地址:https://github.com/square/retrofit

一个Android和Java的的类型安全的HTTP客户端。

介绍

Retrofit将网络请求API转换为一个Java 接口。

public interface MovieService {
    @GET("top250")
    Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
}

Retrofit生成一个MovieService的接口实现。

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.douban.com/v2/movie/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

MovieService movieService = retrofit.create(MovieService.class);

MovieService可以创建一个同步或者异步的远程服务器请求:Call

Call<MovieEntity> topMovie = movieService.getTopMovie(0, 1);

使用注解来描述HTTP请求:

  • 支持URL参数替换和查询。
  • 将对象转化为一个Request Body(例如:JSON、协议缓冲区)。
  • 多部分Request Body和文件上传。

API介绍

为接口的方法添加注解,其参数指明这个请求如何操作。

请求方法

每个方法必须含有HTTP注解(请求方法和相对URL地址)。有5个内置的注解:GET, POST, PUT, DELETE, and HEAD。相对URL地址在注解中指定。

@GET("top250")

同样,可以在URL上指定查询参数。

@GET("users/list?sort=desc")

URL操作

一个请求的URL可以使用替换块和参数来进行URL的动态的替换。替换块的格式:{字符串}。需要替换的部分需要使用相同的字符串和@Path注解。

@GET("{type}250")
Call<MovieEntity> getTopMovie(@Path("type") String type,@Query("start") int start, @Query("count") int count);

同样可以添加查询参数

@GET("top250")
Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);

对于复杂的查询参数组合,可以使用Map集合。

@GET("{type}250")
Call<MovieEntity> getTopMovie(@Path("type") String type,@QueryMap Map<String,Integer> options);

Map<String,Integer> options = new HashMap<>();
options.put("start",1);
options.put("count",2);
Call<MovieEntity> topMovie = movieService.getTopMovie("top",options);

请求主体

使用@Body可以将一个对象作为HTTP的请求主体。

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

指定的对象将使用”Retrofit”指定的转换器进行转换。如果没有添加转换器,就只可以使用RequestBody

FORM ENCODED 和 MULTIPART

方法同样可以声明表单编码和复合数据。

表单编码数据发送当存在@FormUrlEncoded注解。每个键值对的key为@Filed的部分,Value为Object。

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

使用@Multipart来实现Multipart的请求。使用@Part注解来声明内容。

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

Multipart parts使用Retrofit的转换器,或者实现RequestBody

请求头操作

使用@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,头就会被忽略掉。另外,valeu会进行toString

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

如果请求头需要应用在每个请求上,请使用’OkHttp interceptor’

同步和异步

每个Call实例可以执行同步或者异步请求。每个实例只能使用一次,但是可以使用clone()方法创建一个新的实例来操作。

在Android中,callback会在UI线程中执行,在JVM上,callback会在请求执行的线程上执行。

Retrofit的配置

Retrofit是一个将HTTP的API接口转化为可被调用的对象的类。默认的,Retrofit提供默认的配置,当然,你可以自定义。

转换器

默认情况下,Retrofit只能反序列化HTTP的主体到okhttpResponseBody,并且@Body注解只能接收RequestBody的类型数据。

转换器可以被添加来支持其它类型。下面是6个流行的序列化库来方便操作。

*   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

*   Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

例子:生成一个使用Gson反序列的API接口实现类,通过GsonConverterFactory转换器。

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

自定义转换器

Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.

混淆器

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值