前言
一次偶然的机会,我学习了retrofit,使用起来十分方便,并且使代码的逻辑思路都清晰起来,如果配合RxJava,可以省掉大部分重复的代码,可以说,这一个网络框架是当前最火热的,让我们来起学习吧!
1.Retrofit介绍
Refrofit是由Square公司基于okhttp进一步封装而成的,
- Retrofit特点
1.减少解耦,降低耦合,不同api互不干扰
2.使用注解方式,代码简洁,易懂,易上手
3.采用建造者模式,开发简便
- Retrofit来由
retrofit是改造的意思,所以说是Square公司在okhttp基础上改造,进一步封装,但是主要的网络请求还是okhttp,retrofit通过注解的方式,将数据及一些参数提交给okhttp,然后okhttp返回结果给retrofit并回馈给开发用户
- Retrofit要求
Android 2.3及以上,java最低要求1.7
2.Retrofit使用
1.添加依赖包
AndroidStudio下添加到gradle
compile 'com.squareup.retrofit2:retrofit:2.3.0'
Eclipse下添加包
1.如果AndroidStudio下已经开启了混淆,请添加如下代码
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
2.支持返回对象的类型,请添加这些包
// 常用
compile 'com.squareup.retrofit2:converter-gson:2.3.0'//返回gons类型
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'//返回String类型
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'//适配Rxjava2还需要配置RxJava2环境,可以关注我,后续会讲到
compile 'com.squareup.retrofit2:converter-jackson:2.3.0'//返回json类型
// 不常用
compile 'com.squareup.retrofit2:converter-moshi:2.3.0'//返回moshi类型
compile 'com.squareup.retrofit2:converter-protobuf:2.3.0'//返回protobuf类型
compile 'com.squareup.retrofit2:converter-wire:2.3.0'//返回wire类型
compile 'com.squareup.retrofit2:converter-simplexml:2.3.0'//返回simplexml类型
3.添加接口
public interface RetrofitServer {
/**
* get请求
* @param id 请求参数
* value="相对地址"
* @return 返回call对象(String)返回字符串
*/
@GET(value="test")
Call<String> get(@Query("id")String id);
}
4.请求
/**
*
* @param url 请求地址最后一个字符需要为"/"不然报错,例如:http://www.baidu.com/
* @param id 请求参数
* @return 返回String类型
*/
public String Retrofit_Get_String(String url,String id){
//创建实例并调用baseUrl()方法传入一个地址,
// addConverterFactory()添加转换器,将返回的body变为String类型
// ,需要添加compile 'com.squareup.retrofit2:converter-scalars:2.3.0'依赖
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
//利用Retrofit创建一个代理对象
RetrofitServer server=retrofit.create(RetrofitServer.class);
Call<String> call=server.get(id);
//用法和okhttp一致
//方法一,自行线程调度
try {
Response<String> responseBody=call.execute();
return responseBody.body();
} catch (IOException e) {
e.printStackTrace();
}
//方法二,无需线程调度
// call.enqueue(new Callback<String>() {
// @Override
// public void onResponse(Call<String> call, Response<String> response) {
// // TODO: 2017/9/11 success
// Log.d("TAG",response.body());
// }
// @Override
// public void onFailure(Call<String> call, Throwable t) {
// TODO: 2017/9/11 error
// t.printStackTrace();
// }
// });
return null;
}
5.接口定义
1.请求方法:
@GET(value="test2")
Call<String> get(@Query("id")String id);
@GET("一段字符串拼接baseUrl")
@POST()
@PUT()
@DELETE()
@Path()
@HEAD()
@OPTIONS()
//@HTTP可替代上面7种,例如:get请求
/**
* @method: 请求方法
* @path: 路径 {id} 对应@Path("id")标记的值
*/
@HTTP(method = "GET",path = "test/{id}")
Call<String> http(@Path("id")String pt);
2.标记类:
@FormUrlEncoded
@HTTP(method = "GET",path = "test/{id}")
Call<String> httpf(@Path("id")String pt);
@FormUrlEncoded//请求体是一个表单
@Multipart//请求体是一个支持文件上传的表单
@Streaming//返回数据比较大时使用这个注解(如下载文件)
3.参数类:
@GET(value="test2")
Call<String> get(
@Query("id")String id);
@Headers()//请求头
@Header()//不固定值的请求头
//非表单
@Body()//非表单请求体
//用于表单配合 @FormUrlEncoded标记
@Field()//表单字段
@FieldMap()//表单字段Map<String,String>
//配合 @Multipart标记
@Part()
@PartMap()//表单字段Map<Stirng,RequestBody>
//用于url
@Path()//填充占位符{}
@Query()//和上面的@Field() @Part()功能差不多
@QueryMap()//和上面的 @FieldMap() @PartMap()功能差不多