1、什么是Retrofit 2.0 ?
github上的介绍是A type-safe HTTP client for Android and Java.翻译过来就是一个用于Android和Java的类型安全HTTP客户端。底层实际上就是封装了okhttp。
本质的工作流程:
客户端使用Retrofit 进行网络请求,封装请求方法、请求参数、Header、Ur等信息后 ,之后由 OkHttp 完成后续的请求操作。
在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,Retrofit根据用户的需求对结果进行解析。
2、基本使用
- 导入依赖
dependencies {
implement 'com.squareup.retrofit2:retrofit:2.0.2'
// Retrofit库
}
- 创建接口,例如
public interface GetRequest_Interface {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation> getCall();
// @GET注解的作用:采用Get方法发送网络请求
// getCall() = 接收网络请求数据的方法
// 其中返回类型为Call<*>,*是接收数据的类(即上面定义的Translation类)
// 如果想直接获得Responsebody中的内容,可以定义网络请求返回值为Call<ResponseBody>
}
- 创建retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") // 设置网络请求的Url地址
.addConverterFactory(GsonConverterFactory.create()) // 设置数据解析器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平台
.build();
这里创建实例采用的建造者模式
一行一行看。首先是第一行声明并调用buidler,第二行添加了网络请求的url地址,第三行设置了数据解析器,所谓数据解析器就是将服务器返回的数据,通过哪种方式进行解析,获取想要格式的数据。可以使用自带的解析器,也可以自定义数据解析器。
数据解析器 | Gradle依赖 |
---|---|
Gson | com.squareup.retrofit2:converter-gson:2.0.2 |
Jackson | com.squareup.retrofit2:converter-jackson:2.0.2 |
Simple XML | com.squareup.retrofit2:converter-simplexml:2.0.2 |
Protobuf | com.squareup.retrofit2:converter-protobuf:2.0.2 |
Moshi | com.squareup.retrofit2:converter-moshi:2.0.2 |
Wire | com.squareup.retrofit2:converter-wire:2.0.2 |
Scalars | com.squareup.retrofit2:converter-scalars:2.0.2 |
第四行设置一个网络请求的适配器,和上面的类似,同样有自带的适配器。
网络请求适配器 | Gradle依赖 |
---|---|
guava | com.squareup.retrofit2:adapter-guava:2.0.2 |
Java8 | com.squareup.retrofit2:adapter-java8:2.0.2 |
rxjava | com.squareup.retrofit2:adapter-rxjava:2.0.2 |
- 创建接口实例
// 创建 网络请求接口 的实例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//对 发送请求 进行封装
Call<Reception> call = request.getCall();
- 发起请求,处理数据
//发送网络请求(异步)
call.enqueue(new Callback<Translation>() {
//请求成功时回调
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
//请求处理,输出结果
response.body().show();
}
//请求失败时候的回调
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("连接失败");
}
});
// 发送网络请求(同步)
Response<Reception> response = call.execute();
3、创建接口的注解讲解
注解可以划分三类,分别是网络请求方法,标记类,网络请求参数。
类型 | 注解名称 | 解释 |
---|---|---|
网络请求方法 | @GET | 分别对应http协议中的方法,接收一个url地址 |
@POST | ||
@PUT | ||
@DELETE | ||
@PATH | ||
@HEAD | ||
@OPTIONS | ||
@HTTP | 用于替换以上7个注解以及拓展更多的功能 |
再看这个例子。设置了方法是get方法,注意这里的url应该分为两部分,第一部分是上文中创建retrofit实例时,通过设置baseUrl添加的url,第二部分是注解中方法后面跟随的url地址。
所以完整的url地址=第一部分+第二部分
public interface GetRequest_Interface {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation> getCall();
// @GET注解的作用:采用Get方法发送网络请求
// getCall() = 接收网络请求数据的方法
// 其中返回类型为Call<*>,*是接收数据的类(即上面定义的Translation类)
}
接下来是@HTTP的使用,如下例。
public interface GetRequest_Interface {
/**
* method:网络请求的方法(区分大小写)
* path:网络请求地址路径
* hasBody:是否有请求体
*/
@HTTP(method = "GET", path = "blog/{id}", hasBody = false)
Call<ResponseBody> getCall(@Path("id") int id);
// {id} 表示是一个变量
// method 的值 retrofit 不会做处理,所以要自行保证准确
}
类型 | 注解名称 | 解释 |
---|---|---|
标记类 | @FormUrlEncoded | 表示请求体是一个Form表单 |
@Multipart | 表示请求体是一个支持文件上传的Form表单 | |
@Streaming | 表示返回的数据以流的形式返回;适合量较大的数据(如果没有使用该注解,默认将数据存入内存中;之后的读取数据也是在内存中进行) |
a. @FormUrlEncoded
- 作用:表示发送form-encoded的数据
每个键值对需要用@Filed来注解键名,随后的对象需要提供值。
b. @Multipart
- 作用:表示发送form-encoded的数据(适用于 有文件 上传的场景)
每个键值对需要用@Part来注解键名,随后的对象需要提供值。
public interface GetRequest_Interface {
/**
*表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
* <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值
*/
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
/**
* {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
* 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
*/
@POST("/form")
@Multipart
Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);
}
// 具体使用
GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
// @FormUrlEncoded
Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);
// @Multipart
RequestBody name = RequestBody.create(textType, "Carson");
RequestBody age = RequestBody.create(textType, "24");
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
类型 | 注解名称 | 解释 |
---|---|---|
网络请求参数 | @Headers | 添加请求头 |
@Header | 添加不固定值的Header | |
@Body | 用于非表单请求体 | |
@Field | 向Post表单传入键值对 | |
@FiledMap | ||
@Part | 用于表单字段:适用于有文件上传的情况 | |
@PartMap | ||
@Query | 用于表单字段,功能同@Field和@FiledMap (区别在于@Field的数据体现在请求体上;而@Query体现在URL上) | |
@QueryMap | ||
@Path | URL缺省值 | |
@URL | URL设置 |
a. @Header & @Headers
- 作用:添加请求头 &添加不固定的请求头
- 具体使用如下:
// @Header@GET("user")Call<User> getUser(@Header("Authorization") String authorization)// @Headers@Headers("Authorization: authorization")@GET("user")Call<User> getUser()// 以上的效果是一致的。// 区别在于使用场景和使用方式// 1. 使用场景:@Header用于添加不固定的请求头,@Headers用于添加固定的请求头// 2. 使用方式:@Header作用于方法的参数;@Headers作用于方法
b. @Body
- 作用:以
Post
方式 传递 自定义数据类型 给服务器 - 特别注意:如果提交的是一个Map,那么作用相当于
@Field
不过Map要经过
FormBody.Builder
类处理成为符合 Okhttp 格式的表单,如:
FormBody.Builder builder = new FormBody.Builder();builder.add("key","value");
c. @Field & @FieldMap
- 作用:发送 Post请求 时提交请求的表单字段
- 具体使用:与
@FormUrlEncoded
注解配合使用
public interface GetRequest_Interface { /** *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded) * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);/** * Map的key作为表单的键 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);}// 具体使用 // @Field Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24); // @FieldMap // 实现的效果与上面相同,但要传入Map Map<String, Object> map = new HashMap<>(); map.put("username", "Carson"); map.put("age", 24); Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);
d. @Part & @PartMap
- 作用:发送 Post请求 时提交请求的表单字段
与@Field的区别:功能相同,但携带的参数类型更加丰富,包括数据流,所以适用于 有文件上传 的场景
- 具体使用:与
@Multipart
注解配合使用
public interface GetRequest_Interface { /** * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型 * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息), */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file); /** * PartMap 注解支持一个Map作为参数,支持 {@link RequestBody } 类型, * 如果有其它的类型,会被{@link retrofit2.Converter}转换,如后面会介绍的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter} * 所以{@link MultipartBody.Part} 就不适用了,所以文件只能用<b> @Part MultipartBody.Part </b> */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file); @POST("/form") @Multipart Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args);}// 具体使用 MediaType textType = MediaType.parse("text/plain"); RequestBody name = RequestBody.create(textType, "Carson"); RequestBody age = RequestBody.create(textType, "24"); RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "这里是模拟文件的内容"); // @Part MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file); Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart); ResponseBodyPrinter.printResponseBody(call3); // @PartMap // 实现和上面同样的效果 Map<String, RequestBody> fileUpload2Args = new HashMap<>(); fileUpload2Args.put("name", name); fileUpload2Args.put("age", age); //这里并不会被当成文件,因为没有文件名(包含在Content-Disposition请求头中),但上面的 filePart 有 //fileUpload2Args.put("file", file); Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //单独处理文件 ResponseBodyPrinter.printResponseBody(call4);}
e. @Query和@QueryMap
- 作用:用于
@GET
方法的查询参数(Query = Url 中 ‘?’ 后面的 key-value)
如:url = http://www.println.net/?cate=android,其中,Query = cate
- 具体使用:配置时只需要在接口方法中增加一个参数即可:
@GET("/") Call<String> cate(@Query("cate") String cate);}// 其使用方式同 @Field与@FieldMap,这里不作过多描述
f. @Path
- 作用:URL地址的缺省值
- 具体使用:
public interface GetRequest_Interface { @GET("users/{user}/repos") Call<ResponseBody> getBlog(@Path("user") String user ); // 访问的API是:https://api.github.com/users/{user}/repos // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用) }
g. @Url
- 作用:直接传入一个请求的 URL变量 用于URL设置
- 具体使用:
public interface GetRequest_Interface { @GET Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll); // 当有URL注解时,@GET传入的URL就可以省略 // 当GET、POST...HTTP等方法中没有设置Url时,则必须使用 {@link Url}提供}
参考 https://www.jianshu.com/p/a3e162261ab6/