本文主要介绍Retrofit的使用
一、定义
一个类型安全的 HTTP客户端请求框架,适用于Android和Java
Retrofit是一个Restful的HTTP网络请求框架的封装。网络请求实际上由OKHttp完成的,而Retrofit仅负责网络请求接口的封装
二、依赖添加
Gradle方式:
implementation 'com.squareup.retrofit2:retrofit:(insert latest version)'
当前最新版本 2.9.0
三、混淆配置
如果使用R8编译器(Gradle插件3.4.0及以上版本默认)则不需要配置,压缩和混淆规则已经打包Jar中,R8能够自动解释运行。
使用ProGuard,则需要手动配置如下规则:
四、框架使用
4.1、使用示例
- 步骤1:将HTTP API转换成Java接口
public interface WanAndroidService {
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index);
}
复制代码
- 步骤2:使用Retrofit生成Java接口(对应步骤1的
WanAndroidService)的实现
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
WanAndroidService wanAndroidService = retrofit.create(WanAndroidService.class);
复制代码
- 步骤3:使用Java接口(
WanAndroidService)创建Call对象,Call对象可以向Web服务器发起同步或者异步HTTP请求
Call<JsonObject> articles = wanAndroidService.getArticles(0);
JsonObject body = articles.execute().body();
复制代码
System.out.println("响应数据:"+body);打印结果:

4.2、API说明
Retrofit通过在接口方法和参数添加注解的方式来处理请求逻辑,
4.2.1、请求方法
每个接口方法都必须有一个指定请求方法和相对URL的注解。Retrofit一共有8个内置请求方法注解:HTTP, GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD。请求的相对URL通过注解属性指定
- 示例:
@GET("users/list")
4.2.2、URL配置
请求URL可以通过方法中替换块和参数动态的修改。一个可替换块是由{和}符号包围的字母数字字符串。相应的参数必须使用@Path注解,并且注解属性值保持和代码块字符串一致
- 示例1:
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index);
复制代码
- 示例2:(使用
@Query注解添加请求参数)
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @Query("cid") int cid);
复制代码
- 示例3:(复杂的参数组合可以使用map集合的方式)
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @QueryMap Map<String,String> params);
复制代码
4.2.3、请求体
使用@Body注解可以指定一个对象作为请求体
该对象将使用再Retrofit实例创建时指定的转换器进行转换,如果不添加转换器,则默认只能使用RequestBody
- 示例:
@POST("user/login")
Call<JsonObject> login(@Body User user);
复制代码
4.2.4、FORM ENCODED和MULTIPART
方法也能被声明来发送from-encoded和multipart数据
方法使用@FromUrlEncoded注解修饰时,将发送from-encoded数据。每个健值对使用包含名称和提供值的参数对象的@Field注解进行注解
- 示例:
@FormUrlEncoded
@POST("user/login")
Call<JsonObject> login(@Field("username") String username, @Field("password") String password);
复制代码
方法使用@Multipart注解修饰时,将发送Multipart请求。请求Parts使用@Part注解注解
Multipart parts将使用Rotrofit提供的转换器之一或者自定义实现RequestBody来处理参数的序列化
- 示例:
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
复制代码
4.2.5、请求头配置
使用@Headers可以设置静态请求头
- 示例:
@Headers("Accept-Encoding: gzip, deflate")
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @Query("cid") int cid);
@Headers({
"Accept: application/json,application/xml,application/xhtml+xml,text/html;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding: gzip, deflate"
})
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @Query("cid") int cid);
复制代码
- ⚠️:请求头不会相互覆盖。具有相同名称的请求头都会包含在请求中
使用@Header注解可以动态的修改请求头。必须为@Header提供相应的参数,如果参数值为null,则这个Header头会被忽略,否则将使用参数值的toString结果做为请求头的值
- 示例:
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Header("test") String test, @Path("index") int index);
复制代码
和请求参数相似,对应复杂的请求头,可以使用Map集合
- 示例:
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@HeaderMap Map<String, String> test, @Path("index") int index);
复制代码
需要在每个请求上添加请求头参数,可以使用OkHttp interceptor实现
4.2.6、同步 VS 异步
call实例可以同步或者异步执行。每个实例只能执行一次,但是使用clone()方法可以重新创建一个可使用的实例
在Android设备上,异步回调方法将会在主线程中执行。在JVM上,异步回调方法将在会请求执行的线程中执行
五、Retorfit配置
Retrofit是将API接口转换为可调用对象的类。默认情况下,Retrofit将会为平台提供合理的默认值,同时也允许自定义
5.1、转换器
默认情况下,Retrofit仅能将Http响应反序列化为OkHttp的ResponseBody类型,并且对于@Body仅能接受RequestBody类型
添加转换器可以实现对其他类型的支持。Retrofit提供相似的模块,封装最受欢迎的几个序列化库,方便用户使用
- 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
- JAXB: com.squareup.retrofit2:converter-jaxb
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
如下是GsonConverterFactory类的使用实例,生成WanAndroidService接口的实现,使用Gson库反序列化响应数据
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
WanAndroidService wanAndroidService = retrofit.create(WanAndroidService.class);
复制代码
5.2、自定义转换器
我们可以轻松自定义转换器,如果我们需要使用Retrofit没有提供支持的格式(例如:YAML,txt,自定义格式)的API进行通信,或者需要使用不同的库来支持现有的格式。
自定义方式:创建Converer.Factory的子类,并在构建适配器时传入该子类的实例






![[物联网]4G模块openCPU通信之http通信-一一网](https://www.proyy.com/skycj/data/images/2021-04-26/61560a580373acaab5e02cae974d62b5.png)












![[02/27][官改] Simplicity@MIX2 ROM更新-一一网](https://www.proyy.com/wp-content/uploads/2020/02/3168457341.jpg)


![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)